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));
});
});
})();