Skip to content

Instantly share code, notes, and snippets.

@lucnap
Last active May 3, 2016 17:00
Show Gist options
  • Save lucnap/868af782d26dda97762c9ecbff0b6920 to your computer and use it in GitHub Desktop.
Save lucnap/868af782d26dda97762c9ecbff0b6920 to your computer and use it in GitHub Desktop.
Javascript Nodejs async execution with waterfall method
/*
With async.waterfall the functions are executed one after the other and the result of each one is used
to call the next function.
fn0 -> fn1(resultFromfn0, callback) -> fn2(resultFromfn1, callback) -> fn3(resultFromfn2, callback)
*/
var async = require("async");
function fn0(myParam, callback) {
setTimeout(function(){
if (myParam === "ciao") {
callback(null, myParam + " xxxx");
} else {
callback("error 123", null);
}
}, 400);
}
function fn1(paramFromPreviousFn, callback) {
setTimeout(function(){
console.log("I'm fn1 and you called me with " + paramFromPreviousFn);
var ret = paramFromPreviousFn + ' (processed by fn1)';
callback(null, ret); // err, result
}, 350);
}
function fn2(customParam, paramFromPreviousFn, callback){
setTimeout(function(){
console.log("I'm fn2 and you called me with " + customParam + " + " + paramFromPreviousFn);
var ret = paramFromPreviousFn + ' (processed by fn2)';
callback(null, ret); // err, result
}, 100);
}
// example with and without custom params
async.waterfall([fn0.bind(null, "ciao"), fn1, fn2.bind(null, "hello")], function(err, result) {
console.log("final result = " + result);
console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment