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.
- tasks: It refer to the array of async functions. Each function runs and sends the result as an argument to the next function.
- callback: Once all the functions are completed, then callback runs. This will have arguments from the result of the last task’s callback. The callback is optional. It is invoked with (err,[results]).
Note: To use the async.waterfall function, we need to import it first.
Outout: The async.waterfall() will pass only the result of the last function called to the main callback.
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.
- tasks: It is a collection of tasks or functions in series.
- callback: It is an optional argument, invoked when error occurs in any of the function, otherwise, it gets the array of the results of all the tasks.
Note: To use the async.series function, we need to import it first.
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:
- The async.waterfall allows each function to pass on its results to the next function, while async.series passes all the task’s results to the final callback.
- The async.waterfall() will pass only the result of the last function called to the main callback. But, the async.series will pass all the task’s result to the main callback.