6

我正在使用async library中的一些函数,并想确保我了解它们在内部是如何做事的;但是,我坚持 async.waterfall在此处实施)。实际的实现使用了库中的其他函数,没有太多经验,我发现很难理解。

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

文档,瀑布的描述:

连续运行任务数组,每个函数将其结果传递给数组中的下一个。但是,如果任何任务将错误传递给自己的回调,则不会执行下一个函数,并且会立即调用主回调并返回错误。

一个例子:

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'    
});
4

2 回答 2

8

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

首先,功能:

function waterfall(arr, cb){} // takes an array and a callback on completion

现在,我们需要跟踪数组并对其进行迭代:

function waterfall(arr, cb){
    var fns = arr.slice(); // make a copy
}

让我们从处理传递的和空的数组开始,通过添加一个额外的参数来传递结果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
        });
    }
}

那很好:

waterfall([], function(err, data){
    console.log("Done!");
});

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

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); 
    });
}

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

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

于 2015-03-06T21:50:20.317 回答
0

对于那些喜欢简短的人:

function waterfall(fn, done){
   fn.length ? fn.shift()(function(err){ err ? done(err) : waterfall(fn, done) }) :  done();
}
于 2015-09-10T05:00:16.007 回答