Trusted answers to developer questions

What are async functions in Async?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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.

RELATED TAGS

javascript
async
asynchronous programming
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?