Skip to content
This repository has been archived by the owner on Jul 31, 2021. It is now read-only.

Asynchronous for/each loops with async/await in Node.JS

License

Notifications You must be signed in to change notification settings

axelrindle/node-async-for-each

Repository files navigation

Deprecated: Just use native async/await with for/of or for/in

node-async-for-each

Asynchronous for/each loops with async/await in Node.JS

Install

$ npm i @axelrindle/async-for-each

Usage

const asyncForEach = require('@axelrindle/async-for-each');
const array = [1, 2, 3, 4, 5];

const sleep = duration => {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, duration);
  });
};

// wrap in an async function to wait for the loop to finish
(async () => {
  await asyncForEach(array, async (el) => {
    console.log(`Sleeping for ${el} seconds...`);
    await sleep(el * 1000);
  });
  console.log('Done!');
})();

Credits

Credit goes to Sebastien Chopin for providing an excellent tutorial.

License

MIT