I'm not looking for any solution in any particular language, I just want to understand what are the good practices in the area of running async tasks from a loop.
This is what I have thought of so far:
var callAcc = 0;
var resultArr = [];
for (var k = 0; k < 20; k++) {
callAcc ++;
asyncFunction("variable")
.then(function (result) {
resultArr.push(result);
if (callAcc === resultArr.length) {
// do something with the resultArr
}
})
.catch(function (err) {
console.warn(err);
});
}
At this point, I'm just using a sync variable that will only let me proceed once I have all of the async tasks complete. However, this feels hacky and I was wondering if there was some kind of design pattern to execute aync tasks from a loop
EDIT: Based on the proposed solutions, this is what i ended up using
var promises = [];
for (var i = 0; i < 20; i ++) {
promises.push(asyncFunction("param"));
}
Promise.all(promises)
.then(function (result) {
console.log(result);
})
.catch(function (err) {
console.warn(err);
});
Thank you everyone!
Promise.all...developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…