Looping with async await
suggest changeWhen using async await in loops, you might encounter some of these problems.
await inside a non-async forEach callback is a syntax error. An async function is strict, so the bare assignment data = ... would also throw ReferenceError. Declare data.
(async() => {
const data = [1, 2, 3, 4, 5];
data.forEach(e => {
const i = await somePromiseFn(e);
console.log(i);
});
})();
The await belongs to the callback, and that callback is not async.
The interpreter protects us from making the above error, but if you add async to the forEach callback no errors get thrown. You might think this solves the problem, but it won’t work as expected.
Example:
(async() => {
const data = [1, 2, 3, 4, 5];
data.forEach(async(e) => {
const i = await somePromiseFn(e);
console.log(i);
});
console.log('this will print first');
})();
This happens because the callback async function can only pause itself, not the parent async function.
A hand-rolled asyncForEach can return a promise that settles when every callback has finished. A for...of or while loop is clearer.
(async() => {
const data = [1, 2, 3, 4, 5];
for (const e of data) {
const i = await somePromiseFn(e);
console.log(i);
}
console.log('this will print last');
})();
But there’s another catch. This solution will wait for each call to somePromiseFn to complete before iterating over the next one.
This is great if you actually want your somePromiseFn invocations to be executed in order but if you want them to run concurrently, you will need to await on Promise.all.
(async() => {
const data = [1, 2, 3, 4, 5];
const p = await Promise.all(data.map(async(e) => await somePromiseFn(e)));
console.log(...p);
})();
Promise.all waits until every promise is fulfilled. If one rejects, the combined promise rejects. These examples run in current engines. async does not need a Babel stage-3 preset. somePromiseFn can be a delayed echo:
function somePromiseFn(n) {
return new Promise((res, rej) => {
setTimeout(() => res(n), 250);
});
}