Using awaitin a loop forinside a function asyncprovides the expected execution result, awaiting the completion of the current Promiseinside 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));
});
}
})()
Run codeWhy Array.prototype.forEach()doesn’t it provide the same functions as those awaiting execution of the current Promiseone when it is awaitused in the callback passed to .forEach()?
const story = [1,2,3,4,5];
(async() => {
story.forEach(async function(chapterUrl) {
await new Promise(function(resolve) {
setTimeout(function() {
resolve(chapterUrl)
}, 1000)
}).then(function(chapter) {
document.body
.appendChild(document.createTextNode(chapter));
});
});
})();
Run code
source
share