Async Utility Module

repository·master·Indexed 12 days ago

https://github.com/caolan/async

A powerful utility module for managing asynchronous JavaScript operations in Node.js and browsers. Version 3.2.6 provides higher-order functions and common patterns for control flow, including iteration, mapping, and concurrency limiting. It supports Node-style error-first callbacks, ES2017 async/await functions, and provides a dedicated pure ESM version via async-es.

Tokens
5.1K
Snippets
21
Records
25
Agent score
97%

What's inside Async

  1. Using ES2017 `async` functions with Async

    master

    Async accepts native async functions. When using them, you do not pass a callback to the iteratee. Instead, you return a value or throw an error. Async will automatically handle the promise resolution/rejection.

    Note: Async can only detect native async functions. For transpiled versions (e.g., via Babel), wrap them in async.asyncify().

    async.mapLimit(files, 10, async file => {
        const text = await util.promisify(fs.readFile)(dir + file, 'utf8')
        const body = JSON.parse(text)
        if (!(await checkValidity(body))) {
            throw new Error(`${file} has invalid contents`)
        }
        return body
    }, (err, contents) => {
        if (err) throw err
        console.log(contents)
    })
    async.mapLimit(files, 10, async file => {
        const text = await util.promisify(fs.readFile)(dir + file, 'utf8')
        const body = JSON.parse(text) // <- a parse error here will be caught automatically
        if (!(await checkValidity(body))) {
            throw new Error(`${file} has invalid contents`) // <- this error will also be caught
        }
        return body // <- return a value!
    }, (err, contents) => {
        if (err) throw err
        console.log(contents)
    })
  2. Binding Context to an Iteratee

    master

    If an iteratee relies on this (e.g., a method from another library), you must use .bind() to attach the correct context before passing it to an Async method. Otherwise, this will be undefined or incorrect within the Async execution context.

    // Correctly binding the context
    async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result) {
        // result is [1, 4, 9]
    });
    async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result) {
        // With the help of bind we can attach a context to the iteratee before
        // passing it to Async. Now the square function will be executed in its
        // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent`
        // will be as expected.
    });
  3. Install and use async-es

    master

    The async-es package is a version of the async utility module optimized for building with webpack. It provides powerful functions for managing asynchronous JavaScript workflows. While the original async package is designed for Node.js, async-es is intended for environments where you are using a bundler like webpack (e.g., browser-based applications).

    To use it in a project, install the package via npm:

    npm install --save async-es

    Note: If you are working in a pure Node.js environment without a bundler, you should install the standard async package instead.

    npm install --save async-es
  4. Use Async with ES Modules

    master

    Async includes a .mjs version for compatible bundlers (Webpack, Rollup). Alternatively, you can use the async-es package for a collection of pure ES2015 modules.

    Install async-es:

    $ npm install async-es

    Importing:

    import waterfall from 'async-es/waterfall';
    import async from 'async-es';
  5. Use Async in the Browser

    master

    Async works in any ES2015 environment (Node 6+ and modern browsers). For older environments like IE11, you must transpile the code. You can include the library via a <script> tag using the files in the /dist folder or via a CDN like jsDelivr.

    <script type="text/javascript" src="async.js"></script>
    <script type="text/javascript">
        async.map(data, asyncProcess, function(err, results) {
            alert(results);
        });
    </script>
    <script type="text/javascript" src="async.js"></script>
    <script type="text/javascript">
    
        async.map(data, asyncProcess, function(err, results) {
            alert(results);
        });
    
    </script>
  6. Use Async with TypeScript

    master

    To use Async with TypeScript, install the third-party type definitions. It is recommended to set your tsconfig.json target to es2017 or higher to ensure async functions are preserved.

    Install types:

    npm i -D @types/async

    Recommended tsconfig.json:

    {
      "compilerOptions": {
        "target": "es2017"
      }
    }
  7. Import Async in Node.js

    master

    In a Node.js environment, you can require the entire library or individual methods.

    Require the full library:

    var async = require("async");

    Require individual methods:

    var waterfall = require("async/waterfall");
    var map = require("async/map");
  8. Install and use Async

    master

    Async is a utility module providing functions for managing asynchronous JavaScript operations. It is primarily used in Node.js but is also compatible with browsers.

    Installation

    You can install the main package via npm:

    npm i async

    Module Formats

    • CommonJS/Node.js: Use require('async').
    • ESM/MJS: The main async package includes an ESM/MJS version that works with bundlers like Webpack and Rollup.
    • Pure ESM: A dedicated pure ESM version is available as async-es on npm.
  9. What is an AsyncFunction in Async?

    master

    In the context of this library, an AsyncFunction is a Node-style asynchronous function (also known as Continuation Passing-Style or CPS). It is defined by having a variable number of parameters, where the final parameter is a callback.

    Callback Signature

    The callback must follow the pattern callback(err, results...) and must be called exactly once:

    • On Error: Call callback(err) where err is an Error object.
    • On Success: Call callback(null, result1, result2, ...) where null signals no error and subsequent arguments are the results.

    Support for ES2017 async/await

    Async library methods also accept native ES2017 async functions. When using a native async function:

    • The final callback argument is not passed.
    • A rejected Promise is treated as an error (err).
    • A resolved value is treated as the result.

    Note on Transpilers: If you use async/await through a transpiler like Babel, the library may not detect it as a native async function. In such cases, you must wrap the function with asyncify to ensure it behaves correctly.