Open In App

What is the difference between async.waterfall and async.series?

async.waterfall: This waterfall method runs all the functions(i.e. tasks) one by one and passes the result of the first function to the second, second function’s result to the third, and so on. When one function passes the error to its own callback, then the next functions are not executed. So, the main callback is immediately called with the error. 

Syntax:



waterfall(tasks,callback)

Note: To use the async.waterfall function, we need to import it first.




import waterfall from 'async/waterfall';

Example: 






async.waterfall([
    function(callback) {
        callback(null, 'gfg', 'one');
    },
    function(arg1, arg2, callback) {
        // The arg1 now equals 'gfg'
        // and arg2 now equals 'one'
        callback(null, 'two');
    },
    function(arg1, callback) {
        // The arg1 now equals 'two'
        callback(null, 'complete');
    }
], function (err, result) {
    // Result now equals 'complete'
});

Output: The async.waterfall() will pass only the result of the last function called to the main callback.

complete

async.series: The async.series method runs the functions in the tasks collection in series. Each one runs once the previous function has completed. If any functions in the series pass an error to its callback, no more functions are executed. Then, the callback is immediately called with the value of the error. Otherwise, callback receives an array of results of all the tasks when tasks have completed.
 
 Syntax:

series(tasks,callback)

Note: To use the async.series function, we need to import it first.  




import series from 'async/series';

Example: 




async.series([
    function(callback) {
        // do something...
        callback(null, 'one');
    },
    function(callback) {
        // do something...
        callback(null, 'two');
    }
],
// callback(optional)
function(err, results) {
    /* Results is now equal to
       ['one', 'two'] and this is
       returned from all the tasks
       executed above.*/
});

Output: The  async.series(), once the series have finished, will pass all the results from all the tasks to the main callback.

The main difference between async.waterfall and async.series is that: 


Article Tags :