What are async functions in Async?

Async is a utility module that provides straight-forward, powerful functions for working with asynchronous JavaScript.

An async function (or AyncFunction) in the context of Async is an asynchronous function with a variable number of parameters where the final parameter is a callback.

An async function is also referred to as a “Node-style async function” or a “continuation passing-style function” (CPS).

Syntax

An AsyncFunction has the following signature:
function (arg1, arg2, ..., callback) {}

The callback function has the signature callback(error, results...) and is called once the async function is completed. The first argument will hold any error that may have occurred or null if no error occurred.

Example

In the example below, the async.each() method accepts an AsyncFunction as its second argument. The AsyncFunction is applied to each item (file) in the passed array. In our case, the AsyncFunction is an anonymous function:

// assuming openFiles is an array of file names
async.each(openFiles, function(file, callback) {

    // Perform operation on file here.
    console.log('Processing file ' + file);

    if( file.length > 32 ) {
      console.log('This file name is too long');
      callback('File name too long');
    } else {
      // Do work to process file here
      console.log('File processed');
      callback();
    }
}, function(err) {
    // callback for the async.each function
    // ...
});

Remember, the AsyncFunction can be any JavaScript async function with the function (arg1, arg2, ..., callback) {} signature.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved