Sequentially Executing Promises Inside A For Loop
I am straggling with chaining two promises inside a loop, so that promise number two, does not start until promise one has been resolved. I saw an example with reduce. Could not ge
Solution 1:
Simply avoid for
loops for asynchronous work.
Arrays have functional methods like forEach
and map
for this kind of thing.
var pendingResults = dummyData.accounts.map(function (account) {
returncreateUser(api, {
email: account.email,
password: 'abc123',
connection: 'Username-Password-Authentication'
}).then(function (authInfo) {
console.log("account: ", authInfo);
returncreate(accountsAPIService, authInfo);
});
});
Promise.all(pendingResults).then(function (results) {
// everything is done
});
Solution 2:
See @Tomalak's answer for the actual solution.
The problem is that a for
clause does not create a new scope for the variables. In other words, you code is understood as:
var i, cursorUser, auth0User;
for (i = 0; i < dummyData.accounts.length; i++) {
cursorUser = dummyData.accounts[i];
auth0User = {
// ...
};
// ...
}
When the async promise is resolved, another iteration probably has already overwritten the cursorUser
variable: the then
callback cannot read the value of the iteration that started its promise anymore.
Post a Comment for "Sequentially Executing Promises Inside A For Loop"