Reputation: 727
I'm trying to play a bit with node and async waterfall function. This is my code:
var async = require('async');
var waterfall = function (req, res) {
async.waterfall([
_function1(req),
_function2,
_function3
], function (error, success) {
if (error) { alert('Something is wrong!'); }
console.log("success");
return alert('Done!');
});
};
function _function1 (req) {
return function (callback) {
var something = req.body;
console.log("first");
callback (null, something);
}
}
function _function2 (something, callback) {
return function (callback) {
console.log("second");
var somethingelse = function () { };
callback (err, somethingelse);
}
}
function _function3 (something, callback) {
return function (callback) {
console.log("third");
var somethingmore = function () { };
callback (err, somethingmore);
}
}
waterfall(function(){}, function(){});
But in the output I get only 'first'. Why another callbacks are not called?
Upvotes: 0
Views: 1001
Reputation: 203241
You shouldn't return a function from _function2
and _function3
. The reason it's being done for _function1
is to pass req
in (which can be done in better ways, see below):
function _function2 (something, callback) {
console.log("second");
var somethingelse = function () { };
callback (err, somethingelse);
}
function _function3 (something, callback) {
console.log("third");
var somethingmore = function () { };
callback (err, somethingmore);
}
To get req
into the waterfall, you could use this:
async.waterfall([
function(callback) { return callback(null, req); },
_function1,
_function2,
_function3
], ...);
Or (which I would prefer):
async.waterfall([
_function1.bind(this, req),
_function2,
_function3
], ...);
In both cases, you wouldn't need to return a function from _function1
either:
function _function1 (req, callback) {
var something = req.body;
console.log("first");
callback (null, something);
}
Upvotes: 1