Skip to content

Instantly share code, notes, and snippets.

@eroosenmaallen
Last active September 20, 2023 14:33
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 eroosenmaallen/3fe55a864fdc9e07768a149008f951b3 to your computer and use it in GitHub Desktop.
Save eroosenmaallen/3fe55a864fdc9e07768a149008f951b3 to your computer and use it in GitHub Desktop.
Interaction between async and Array.forEach/.reduce
#! /usr/bin/env node
const arr = [1, 2, 3, 4, 5, 6];
async function main()
{
/** If this block is uncommented, all 6 lines print at the same time,
* after "Done" is printed, even if the forEach is awaited. Nothing awaits
* the individual Promises created for each element.
*
* Starting...
* Done
* - loop 1
* - loop 2
* - loop 3
* - loop 4
* - loop 5
* - loop 6
*
*/
console.log('Starting forEach...');
await arr.forEach(async n => {
await printL(n, 'forEach');
});
console.log('Done forEach');
/** If this block is uncommented, the lines print in sequence, delaying
* before each one, and if the reduce itself is awaited then `done` will
* be printed last. Each resolver awaits the promise from the previous one,
* so all awaits are resolved in order.
*
* Starting...
* - loop 1
* - loop 2
* - loop 3
* - loop 4
* - loop 5
* - loop 6
* Done
*
*/
console.log('Starting reduce');
await arr.reduce(async (previousPromise, n) => {
await previousPromise;
return printL(n, 'reduce');
}, Promise.resolve());
console.log('Done reduce');
}
function printL(n, m)
{
return new Promise((resolve) => {
setTimeout(() => {
console.log(`- loop ${n}, ${m}`);
resolve();
}, 250);
});
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment