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

时间:2015-01-30 17:08:44

标签: javascript node.js asynchronous

我正在尝试关注代码

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 async module

实现正确的同步函数调用

1 个答案:

答案 0 :(得分:3)

您需要将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');
}