Javascript 什么是async.瀑布的简单实现?
我正在使用来自的一些函数,并希望确保我了解它们在内部的工作方式;然而,我被困在Javascript 什么是async.瀑布的简单实现?,javascript,node.js,asynchronous,waterfall,Javascript,Node.js,Asynchronous,Waterfall,我正在使用来自的一些函数,并希望确保我了解它们在内部的工作方式;然而,我被困在async.failter()上。实际的实现使用了库中的其他函数,由于没有太多经验,我发现很难理解 有人能在不担心优化的情况下,提供一个非常简单的实现瀑布功能的实现吗?可能是类似的东西 从中,瀑布的描述: 连续运行函数的任务数组,每个函数传递 将结果发送到数组中的下一个。但是,如果任何任务通过 错误,下一个函数不执行,并且 主回调会立即调用,并出现错误 例如: async.waterfall([ functio
async.failter
()上。实际的实现使用了库中的其他函数,由于没有太多经验,我发现很难理解
有人能在不担心优化的情况下,提供一个非常简单的实现瀑布功能的实现吗?可能是类似的东西
从中,瀑布的描述:
连续运行函数的任务数组,每个函数传递
将结果发送到数组中的下一个。但是,如果任何任务通过
错误,下一个函数不执行,并且
主回调会立即调用,并出现错误
例如:
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'
});
下面是一个简单的实现,通过对函数进行排队来链接函数 首先,功能:
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);
});
}
就这样!我们基本上通过使用递归来克服不能循环回调的事实。说明它
值得一提的是,如果我们用承诺来实现它,我们可以使用for循环。对于那些喜欢保持简短的人:
function waterfall(fn, done){
fn.length ? fn.shift()(function(err){ err ? done(err) : waterfall(fn, done) }) : done();
}
下面是它是否会像前面提到的那样与额外的参数一起工作?