The waterfall
function in async
allows for the execution of asynchronous functions in sequence. After execution, the result values of that function are passed to the next function as arguments if required.
Once, all functions are executed, waterfall
allows a final callback function to be called.
The following program offers an example of how waterfall
can be used.
import waterfall from 'async/waterfall';var radius = 25;waterfall([function(callback){// Getting value of pivar pi = Math.PI// Sending value forwardcallback(null, pi)},function(pi, callback){// Squaring radiusvar square = radius * radius;// Sending both values forwardcallback(null, pi, square)},function(pi, square, callback){// Calculating areaarea = pi * square;// Sending area to final callbackcallback(null, area);}], function(err, result){if (err){// Displaying errorconsole.log(err)}else {// Displaying resultconsole.log(result)}})waterfall([function(callback){// Doing Somethingvar arg1 = 22callback(null, arg1)},function(arg1, callback){try{// Doing somethingvar arg2 = 'something' * arg1;// Sending undefined variable to throw errorcallback(null, arg1, arg2, arg3)}catch (err){// Sending error to final callbackcallback(err.message, null)}},function(arg1, arg2, callback){// Message to be displayed if last function enteredconsole.log("in last function")callback(null, arg2);}], function(err, result){if (err){// Error Displayedconsole.log(err)}else {// Result displayedconsole.log(result)}})
This example shows how waterfall
is designed to act in the case of a successful execution or error. The main waterfall
function takes an array of functions, to be executed in sequence, and an optional final callback function as arguments.
The first waterfall successfully calculates the area of a circle. It has to be noted that in the case of successful execution, the first argument to the callback has to be null
. Each function in the waterfall has, in its arguments, the parameters forwarded by the previous function followed by a callback function. This callback is automatically assigned and defined by the library. The final callback function has an error parameter as its first argument and the result as its next argument.
The second waterfall demonstrates how errors are handled. In the waterfall in the second function, the try catch
blocks detect an error when an undeclared argument is attempted to be passed to the next function. In the catch
block, the callback is called with a non-null value in the first parameter. This tells the module that an error has occurred which, in turn, stops further execution of the waterfall. The final callback is then called to handle the error.
Free Resources