Example:
for (const user of userList) {
await pingUser(user);
console.log(user.name, 'pinged')
}
console.log('done')
Expectations:
- call
pingUser
on each item of the Set - log user name after each ping
- log
done
after they've all been pinged - call
pingUser
"in parallel" (expectation not met)
The closest piece of code I've been using for this pattern is:
await Promise.all([...userList].map(async user => {
await pingUser(user);
console.log(user.name, 'pinged');
}));
console.log('done')
This is quite a mouthful and it awkwardly uses .map+.all to await promises.
Possible solution:
for (const user of userList) async {
await pingUser(user);
console.log(user.name, 'pinged')
}
console.log('done')
Notes
async
here doesn't just define an "async block" but it would be part of thefor
loop itself; the loop would still need to be awaited as a whole.- this is not equivalent to
for () { /* async IIFE */ }
because that would not wait for the IIFEs to complete.
Prior art
ESLint offers a no-await-in-loop
rule which could be elegantly fixed with this async
keyword in some cases