title: jQuery - getJson wait for function inside each loop to finish before continuing
body: <p>I am fetching some data from PHP, the code all works fine and the result of my PHP is a json list sorted by <code>Likes</code>.</p>
  
  <p>getJson result:</p>
  
  <pre><code>[{"ref":"2038", "name":"aaa", "likes":"10"}, 
  {"ref":"2032", "name":"sss", "likes":"9"},
  {"ref":"1875", "name":"off", "likes":"6"},
  {"ref":"0087", "name":"mki", "likes":"3"},
  {"ref":"1256", "name":"qvb", "likes":"3"},
  {"ref":"8754", "name":"dsa", "likes":"2"},
  {"ref":"4359", "name":"ety", "likes":"0"},
  ...]
  </code></pre>
  
  <p>My problem is that when I loop trough the results, a geolocation function is called to calculate the distance of each member. It seems that the geolocation function is not called at the same time and the list becomes mixed up.</p>
  
  <p>My question is : how can I wait for the geolocation function to calculate the distance, append the result on the list and continuing to the next element? I was looking into using <code>promise</code> but I am not sure how to use it with my code.</p>
  
  <p>jQuery:</p>
  
  <pre><code>    function loadAllMembersData() {
  
          var url_featured = "https://example.com/BBB?members=all";
  
          $.getJSON(url_featured, function (result) {
               //10 results
              $.each(result, function (i, field) {
                  var ref = field.ref;
                  var name = field.name;
                  var likes = field.likes;
                  var lat = field.lat;
                  var lng = field.lng;
  
  console.log(i); //index(i) is fine 0 to 9
  
  
  
                  getLocationServices(lat, lng, function (r) {
  
  console.log(i); //index(i) becomes mixed up (2, 3, 0, 6,...) 
  
                      var displayDistance = r + " miles away";
  
                      $("#membersList ul").append('&lt;li&gt;' +
                              '&lt;a href="#" class="item-link item-content" style="padding: 0"&gt;' +
                              '&lt;div&gt;' + displayDistance + '&lt;/div&gt;' +
                              '&lt;div&gt;' + name + '&lt;/div&gt;' +
                              '&lt;div&gt;' + likes + '&lt;/div&gt;' +
                              '&lt;/a&gt;' +
                              '&lt;/li&gt;');
  
                  });
  
  
  
  
              });
          });
      }
  </code></pre>