Open In App

What is Chaining in Node.js ?

Last Updated : 21 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Chaining in Node.js can be achieved using the async npm module. In order to install the async module, we need to run the following script in our directory:

npm init
npm i async

There are two most commonly used methods for chaining functions provided by the async module:

  • parallel(tasks, callback): The tasks is a collection of functions that runs parallel in practice through I/O switching. If any function in the collection tasks returns an error, the callback function is fired. Once all the functions are completed, the data is passed to the callback function as an array. The callback function is optional.
  • series(tasks, callback): Each function in tasks run only after the previous function is completed. If any of the functions throw an error, the subsequent functions are not executed and the callback is fired with an error value. On completion of tasks, the data is passed into the callback function as an array.

Example 1: Parallel Chaining
Filename: index.js




const async = require('async');
  
async.parallel([
    (callback) => {
        setTimeout(() => {
            console.log('This is the first function');
            callback(null, 1);
        }, 500);
    },
    (callback) => {
        console.log('This is the second function');
        callback(null, 2);
    }
], (err, results) => {
    if (err) console.error(err);
    console.log(results);
});


Run index.js file using the following command:

node index.js

Output:

This is the second function
This is the first function
[ 1, 2 ]

Explanation: It is noted that the two functions were executed asynchronously. Hence the output from the second function was received before the first function finished executing due to the setTimeout() method. However, the data is only passed to the callback once both the functions finish execution.

Example 2: Series Chaining
Filename: index.js




const async = require('async');
  
async.series([
    (callback) => {
        setTimeout(() => {
            console.log('This is the first function');
            callback(null, 1);
        }, 500);
    },
    (callback) => {
        console.log('This is the second function');
        callback(null, 2);
    }
], (err, results) => {
    if (err) console.error(err);
    console.log(results);
});


Run index.js file using the following command:

node index.js

Output:

This is the first function
This is the second function
[ 1, 2 ]

Explanation: Unlike the parallel execution, in this case, the second function wasn’t executed until the first function completed its own execution. Similar to the parallel method, the results are only passed to the callback function once all the functions in the tasks collection finish execution.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads