I have a simple array of exactly 10 elements; their key, value pairs return correctly ordered when logged.
$.each( sArray, function(i, k) {
log(i, k);
// log(i, k) returns correctly
// [0] ELEMENT ONE
// [1] ELEMENT TWO
// [2] ELEMENT THREE
});
However, I'm having trouble understanding why when an $.ajax
call is introduced, and the array is logged from there, that the indices return unordered (refreshing page just randomizes the order every time)
$.each( sArray, function(i, k) {
$.ajax({
success: function(data){
log(i, k);
// returns unordered
// [2] ELEMENT TWO
// [1] ELEMENT ONE
// [3] ELEMENT THREE
// [5] ELEMENT FIVE
// [4] ELEMENT FOUR
// etc...
}
});
});
Key, value pairs match, but are just unordered. Can someone explain this behavior? Thank you!
Because AJAX is asynchronous. There's no guaranteed order in which the AJAX operations will complete.
If you need the order to remain consistent then you probably need to complete all of the AJAX operations first and then perform your action on the order of the array. Perhaps something like this:
let promises = [];
$.each( sArray, function(i, k) {
promises.push(
$.ajax({
/.../
success: function(data){
// Do something with data?
// Maybe add it as a property to k?
// For example:
k.data = data;
}
})
);
});
Promise.all(promises).then(function () {
// Here all of the AJAX operations are complete.
// You can again iterate over the array in the order you like:
$.each(sArray, function(i, k) {
log(i, k);
// In this example, k.data should have the data received from AJAX.
});
});