Skip to content

Instantly share code, notes, and snippets.

@westc
Last active August 29, 2019 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/5b72fdf3fa30b62ccc69bad8d8b36758 to your computer and use it in GitHub Desktop.
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.
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();
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();

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment