Example:
for (const user of userList) {
await pingUser(user);
console.log(user.name, 'pinged')
}
console.log('done')
Expectations:
- call
pingUseron each item of the Set - log user name after each ping
- log
doneafter 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
asynchere doesn't just define an "async block" but it would be part of theforloop 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