Notes of Maks Nemisj

Experiments with JavaScript

How to use async/await with forEach ( oneliner )

If you’re already using async/await syntax, you might notice that forEach is not working for asynced functions. In that case you might start doing old style for loops or even for-of loops. Also if you have a bluebird package already installed you can use bluebird.each() instead. In ECMAScript 2018 there is going to be asynchronous iteration, but for those who stuck on older versions I have oneliner, which i use, if i don’t want to install bluebird or other promise library. Definition of each:

const each = (arr, cb, i = 0) => i < arr.length ? Promise.resolve(cb(arr[i++])).then(() => each(arr, cb, i)) : Promise.resolve();

Usage:

await each(['a', 'b', 'c'], async(item) => {
  console.log('this is ', item);
  await new Promise(resolve => setTimeout(resolve, 1000));
});

, , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.