node.js 使用异步瀑布模块同步调用

node.js synchronus call with asyc waterfall module

我正在尝试以下代码

async.waterfall([
  a1, b1, c1  
], function (err, result) {

});
function a1(callback){
// long processing external call 
    setTimeout(function() {
  console.log('delayed str');
}, 5000);
    callback(null, 'one', 'two');
}
function b1(arg1, arg2, callback){
    console.log(arg1)
    callback(null, 'three');
}
function c1(arg1, callback){
    console.log(arg1)

    callback(null, 'done');
}

我期待以下输出

delayed str
one
three

但我得到了以下输出

one
three
delayed str

如何使用 nodejs 异步模块实现正确的同步函数调用

您需要将 callback(null, 'one', 'two'); 调用移至超时,以便在超时期限后调用下一个函数:

async.waterfall([
    a1, b1, c1  
], function (err, result) {

});
function a1(callback){
    setTimeout(function() {
        console.log('delayed str'); 
        callback(null, 'one', 'two');
    }, 5000);
}
function b1(arg1, arg2, callback){
    console.log(arg1)
    callback(null, 'three');
}
function c1(arg1, callback){
    console.log(arg1)
    callback(null, 'done');
}