I am fetching some data from PHP, the code all works fine and the result of my PHP is a json list sorted by Likes
.
getJson result:
[{"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"},
...]
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.
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 promise
but I am not sure how to use it with my code.
jQuery:
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('<li>' +
'<a href="#" class="item-link item-content" style="padding: 0">' +
'<div>' + displayDistance + '</div>' +
'<div>' + name + '</div>' +
'<div>' + likes + '</div>' +
'</a>' +
'</li>');
});
});
});
}