Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
async

What are async functions in Async?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring