Skip to content

Instantly share code, notes, and snippets.

@jacmkno
Last active May 11, 2022 18:23
Show Gist options
  • Save jacmkno/101ac4a91822d3f4e923f045ba13f828 to your computer and use it in GitHub Desktop.
Save jacmkno/101ac4a91822d3f4e923f045ba13f828 to your computer and use it in GitHub Desktop.
for await vs Promise.all
a = [1,2,3,4,5,5,6,7];
op = e => new Promise(s=>setTimeout(()=>{ console.log("N:", e); s(e)}, Math.random()*1000))
do1 = async () => { await Promise.all(a.map(op)); }
do2 = async ()=>{ for await (const e of a) await op(e) }
await do1(); console.log('done');
/* OUTPUT Promise.all
N: 6
N: 5
N: 2
N: 5
N: 4
N: 3
N: 1
N: 7
done
*/
await do2(); console.log('done');
/* OUTPUT for await
N: 1
N: 2
N: 3
N: 4
N: 5
N: 6
N: 7
done
*/
// Hide the imperative "for await" for modern funcional prograaming
const forEachAwait = async (a, op) => { for await (const e of a) await op(e) };
// Try it with a generator
function* makeRangeIterator(start = 0, end = 100, step = 1) {
let iterationCount = 0;
for (let i = start; i < end; i += step) {
iterationCount++;
console.log('G:', i);
yield i;
}
return iterationCount;
}
// A Slower operation
const slowOp = e => new Promise(s=>setTimeout(()=>{ console.log("N:", e); s(e)}, Math.random()*5000))
// See how the generator goes one step at a time, and each item waits for the previous one.
forEachAwait(makeRangeIterator(1,10), slowOp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment