我尝试使用节点和异步瀑布功能。这是我的代码:
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(){});
但是在输出中我只得到了第一个'。为什么不调用另一个回调?
答案 0 :(得分:1)
您不应该从_function2
和_function3
返回功能。它为_function1
完成的原因是通过req
(可以更好的方式完成,见下文):
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);
}
要让req
进入瀑布,您可以使用:
async.waterfall([
function(callback) { return callback(null, req); },
_function1,
_function2,
_function3
], ...);
或(我更喜欢):
async.waterfall([
_function1.bind(this, req),
_function2,
_function3
], ...);
在这两种情况下,您都不需要从_function1
返回一个函数:
function _function1 (req, callback) {
var something = req.body;
console.log("first");
callback (null, something);
}