foreach-async-await

1.0.0 • Public • Published

foreach-async-await

An async/await compatible method with a forEach style signature

Dependencies Build Status Build status Coverage Status Maintainability License: MIT

Installation

npm i foreach-async-await

About

There may have been times where you would like to use an async function inside a forEach loop.

[1, 2, 3, 4].forEach(async (num) => {
    await someAsyncFunction(num);
});

As we know, the above example does not work. @async/foreach is a no frills, no dependencies module that makes iterating with async functions easier. @async/foreach takes advantage of Promise.all under the hood, so your invocations will run concurrently.

Usage

const asyncForEach = require('@async/foreach');
const fs = require('fs');
 
(async () => {
 
    const files = ['./path/to/file1.js', './path/to/file2.js', './path/to/file3.js'];
 
    const filesContent = await asyncForEach(files, async (file, index, array) => {
        console.log('The current index in the array:', index);
        console.log('The entire array:', array);
        await fs.readFile(file, 'utf8');
    });
 
    // Prints the contents of the files read
    console.log(filesContent);
})();

Readme

Keywords

none

Package Sidebar

Install

npm i foreach-async-await

Weekly Downloads

3

Version

1.0.0

License

MIT

Unpacked Size

5.83 kB

Total Files

10

Last publish

Collaborators

  • codearoni