I need some help with handling async calls in JavaScript. I have a for loop, each loop calls an async HttpRequest, and adds its response to an array. I want the program to wait
Since you are using jQuery you can use the Deferred Object to chain promises.
Collect all the promises and use $.when
with spread operator to wait for all promises to resolve. You can use then
to run a function after all ajax requests are resolved.
ES5 Example
$(document).ready(function () {
var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx", "RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff"];
var urls = channels.map(function (x) {
return "https://api.twitch.tv/kraken/channels/" + x;
});
var data = [];
var promises = urls.map(function (url) {
return $.get(url).then(function (response) {
data.push(response);
});
});
$.when.apply($, promises).then(function () {
console.log('done', data);
});
});
ES6 Example
$(document).ready(function() {
var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx","RobotCaleb","thomasballinger","noobs2ninjas","beohoff"];
var urls = channels.map((x) => "https://api.twitch.tv/kraken/channels/" + x);
var data = [];
var promises = urls.map((url) => $.get(url).then((response) => {
data.push(response);
}));
$.when(...promises).then(function() {
console.log('done', data);
});
});