JSFiddle - React, Tailwind, and code Playground
JavaScript
// global variables: find a better way!
var data = [];
var count = 0;
// a function that returns a promise can be "waited for"
var many_requests = function () {
var promise = $.Deferred();
for(var i = 0; i < 10; i++) {
make_one_request(i, promise);
}
return promise; // "I promise one day I'll be an array of responses"
};
var make_one_request = function (index, promise) {
$.ajax({
url : '/echo/json/',
dataType : 'json',
method: 'post',
data: {},
success: function (response) {
// these will run out of order, but your array will be ordered
data[index] = response;
console.log(index);
// if the time has come, resolve the promise
count++;
if (count == 10) {
promise.resolve(data); // OK! I'm an array of responses now!
}
}
});
};
// I will wait until I have an array of response data
$.when(many_requests()).then( function (data) {
// woo!
console.log(data);
});