Javascript - Iterate An Array And Call Jquery Ajax Requests And Wait For A Request Finished Before Moving To Next Request?
I need to iterate an array (or a simple for loop) to run Ajax request to a server. The problem is, to run next element, current Ajax request must finish first. I've tried so far li
Solution 1:
Promise is an async operation, so instead of issuing it in the loop, you need to chain them together, by saying that the next fetch should only happen after (.then
) previous one finishes:
var promise = Promise.resolve();
for (var i = 0; i < 10; i++) {
// You need to use this IIFE wrapper or ES2015+ let otherwise printed `i`
// will always be 10 because interaction between async behavior and closures
(function (i) {
promise = promise.then(function () {
return ajax("select 1 + " + i).then(function(result) {
console.log("i: " + i);
console.log("Result: " + result);
})
})
})(i);
}
promise.then(function () {
console.log("all done");
})
Post a Comment for "Javascript - Iterate An Array And Call Jquery Ajax Requests And Wait For A Request Finished Before Moving To Next Request?"