Using await
in a for
loop within an async
function provides the expected result of the execution awaiting the completion of the current Promise
within the iteration
const story = [1,2,3,4,5];
(async() => {
for (var i = 0; i < story.length; i++) {
await new Promise(function(resolve) {
setTimeout(function() {
resolve(story[i])
}, 1000)
}).then(function(chapter) {
document.body
.appendChild(document.createTextNode(chapter));
});
}
})()
Why does Array.prototype.forEach()
not provide the same functionality of awaiting the fulfillment of the current Promise
when await
is using within the callback passed to .forEach()
?
const story = [1,2,3,4,5];
(async() => {
story.forEach(async function(chapterUrl) {
// does not await for Promise fulfillment
await new Promise(function(resolve) {
setTimeout(function() {
resolve(chapterUrl)
}, 1000)
}).then(function(chapter) {
document.body
.appendChild(document.createTextNode(chapter));
});
});
})();
await
suspends the current function until thePromise
is resolved. When using multipleawait
calls in afor
loop, they are all executed within the same block scope and, thus, wait for the previous one to finish before continuing.When using the
forEach
function, each iteration of the loop is run in its own scope, so eachawait
has no effect on the others.