Paul Somers
1 min readNov 1, 2017

--

Interesting solutions, did you also consider using reduce?

An async function returns a Promise, this means you can do promise reduction on it to chain with reduce and then

// reduce version
async function fizz(arr) {
await arr.reduce((p, e, i) => p.then(async () => {
await foo(e);
}), Promise.resolve());
console.log('done');
}
function foo(x) { // some awaitable func
return new Promise(r => window.setTimeout(
() => r(console.log('foo', x, )),
2000
));
}
fizz([1, 2, 3]); // invoke

If in future we have a forEach which supports async/await then there are only 2 lines to change to transform up back

// The ideal version if forEach worked with async
async function fizz(arr) {
await arr.forEach(async (e, i) => {
await foo(i);
});
console.log('done');
}

--

--