什么是async.waterfall的简单实现?

sga*_*a62 6 javascript asynchronous waterfall node.js

我正在使用异步库中的一些函数,并希望确保我了解它们在内部的工作方式; 但是,我坚持 async.waterfall(在这里实施).实际实现使用了库中的其他功能,没有太多经验,我发现很难遵循.

有人可以在不担心优化的情况下提供一个非常简单的实现来实现瀑布的功能吗?可能与这个答案相当的东西.

文档中,瀑布的描述:

运行函数的tasks数组,每个函数将结果传递给数组中的下一个.但是,如果任何任务将错误传递给它们自己的回调,则不执行下一个函数,并立即调用主回调并显示错误.

一个例子:

async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
      // arg1 now equals 'one' and arg2 now equals 'two'
        callback(null, 'three');
    },
    function(arg1, callback) {
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    // result now equals 'done'    
});
Run Code Online (Sandbox Code Playgroud)

Ben*_*aum 8

好吧,这是一个通过排队来链接函数的简单实现.

首先,功能:

function waterfall(arr, cb){} // takes an array and a callback on completion
Run Code Online (Sandbox Code Playgroud)

现在,我们需要跟踪数组并迭代它:

function waterfall(arr, cb){
    var fns = arr.slice(); // make a copy
}
Run Code Online (Sandbox Code Playgroud)

让我们从处理传递和空数组开始,通过添加一个额外的参数,以便我们可以传递被调用的结果result:

function waterfall(arr, cb, result){ // result is the initial result
    var fns = arr.slice(); // make a copy
    if(fns.length === 0){
        process.nextTick(function(){ // don't cause race conditions
            cb(null, result); // we're done, nothing more to do
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

真好:

waterfall([], function(err, data){
    console.log("Done!");
});
Run Code Online (Sandbox Code Playgroud)

现在,让我们处理实际的东西:

function waterfall(arr, cb, result){ // result is the initial result
    var fns = arr.slice(1); // make a copy, apart from the first element
    if(!arr[0]){ // if there is nothing in the first position
        process.nextTick(function(){ // don't cause race conditions
            cb(null, result); // we're done, nothing more to do
        });
        return;
    }
    var first = arr[0]; // get the first function
    first(function(err, data){ // invoke it
         // when it is done
         if(err) return cb(err); // early error, terminate entire call
         // perform the same call, but without the first function
         // and with its result as the result
         waterfall(fns, cb, data); 
    });
}
Run Code Online (Sandbox Code Playgroud)

就是这样!我们通过使用递归基本上克服了我们无法使用回调循环的事实.这是一个说明它的小提琴.

值得一提的是,如果我们用promises实现它,我们可以使用for循环.