The main difference seems to be that due to the fact that you must iterate through the await responses using an async function in the forEach
version, the replies actually appear out of order.
Last active
August 29, 2019 12:57
-
-
Save westc/5b72fdf3fa30b62ccc69bad8d8b36758 to your computer and use it in GitHub Desktop.
Seeing the difference between using await with Array.prototype.forEach and using await with for...of.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function testForEachReplies(maxSecs = 4) { | |
async function replyIn(secs) { | |
return await { | |
then(res, rej) { | |
setTimeout( | |
_ => res(`I replied after ${secs} second${secs - 1 ? 's' : ''}`), | |
secs * 1e3 | |
); | |
} | |
}; | |
} | |
let replies = []; | |
for (let i = 1; i <= maxSecs; i++) { | |
replies.push(replyIn(i)); | |
for (let j = 1; j < i; j++) { | |
replies.push(replyIn(j)); | |
} | |
} | |
console.log((new Date).toJSON()); | |
replies.forEach(async function (reply) { | |
console.log(await reply); | |
}); | |
console.log((new Date).toJSON()); | |
} | |
testForEachReplies(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function testForOfReplies(maxSecs = 4) { | |
async function replyIn(secs) { | |
return await { | |
then(res, rej) { | |
setTimeout( | |
_ => res(`I replied after ${secs} second${secs - 1 ? 's' : ''}`), | |
secs * 1e3 | |
); | |
} | |
}; | |
} | |
let replies = []; | |
for (let i = 1; i <= maxSecs; i++) { | |
replies.push(replyIn(i)); | |
for (let j = 1; j < i; j++) { | |
replies.push(replyIn(j)); | |
} | |
} | |
console.log((new Date).toJSON()); | |
for (let reply of replies) { | |
console.log(await reply); | |
} | |
console.log((new Date).toJSON()); | |
} | |
await testForOfReplies(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment