nest async.waterfall in async.forEachSeries

nest async.waterfall in async.forEachSeries

本文关键字:async forEachSeries in waterfall nest      更新时间:2023-09-26

我构造了这个简化的小例子来说明我的异步问题:

var array = ["a", "b", "c", "d"];
async.forEachSeries(array, function(entry, callback){
    console.log(entry);
    async.waterfall([
       function(cb){
           console.log("step 1");
           cb(null,  "x");
       },
       function(param, cb){
           setTimeout(function(){console.log(param, "step 2");}, 1000);
           cb(null, "xx");
       },
       function(param, cb){
           console.log(param, "step 3");
           cb("xxx");
       }
    ], function(result, err){
        console.log(result, "waterfall done");
        callback();
    });
}, function(err){
    if(err) console.log("ERROR: "+ err);
});

其输出为

    a
    step 1
    step 3 xx
    end xxx
    b
    step 1
    step 3 xx
    end xxx
    c
    step 1
    step 3 xx
    end xxx
    d
    step 1
    step 3 xx
    end xxx
    step 2 x
    step 2 x
    step 2 x
    step 2 x

如何确保瀑布中的函数等待前一个函数完成?

谢谢

我相信

您必须将cb(null, "xx");放入步骤 #2 的setTimeout回调中。

setTimeout(function() {
    console.log(param, "step 2"); 
    cb(null, "xx"); 
}, 1000);