Javascript Node.js中For循环中的async.瀑布
在Javascript Node.js中For循环中的async.瀑布,javascript,node.js,async.js,Javascript,Node.js,Async.js,在for循环中使用时,似乎for循环在嵌套的async.fallet完成其所有步骤之前迭代。如何避免这种情况 for(var i = 0; i < users.length; i++ ) { console.log(i) async.waterfall([ function(callback) { callback(null, 'one', 'two'); }, function(arg1, arg
for
循环中使用时,似乎for
循环在嵌套的async.fallet
完成其所有步骤之前迭代。如何避免这种情况
for(var i = 0; i < users.length; i++ ) {
console.log(i)
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'
console.log('done')
});
}
所需输出
0
1
2
3
4
done
done
done
done
done
0
done
1
done
2
done
3
done
4
done
您需要应用递归模式。我的建议是这样的
function foo(properties, callback){
/*Initialize inputs w/ useful defaults. Using a properties object simply because it looks nicer, you can use individual values if you'd like.*/
properties.start = properties.start || 0;
properties.end = properties.end || 10; //or any default length
properties.data = properties.data || [];
async.waterfall([
function(callback) {
},
function(arg1, arg2, callback) {
/* arg1 now equals 'one' and arg2 now equals 'two' you can do something with that before continuing processing */
},
function(arg1, callback) {
/* arg1 now equals 'three', you can do something with that before continuing processing */
}
], function (err, result) {
// result now equals 'done'
// now that we have fully processed one record, we need to either finish or recurse to the next element.
if(properties.index >= properties.end){
callback();
}
else{
properties.index++;
foo(properties, callback);
}
})}
我已将回调传递到每个函数回调中。如果愿意,您可以选择以这种方式提前结束递归,或者您可以在该位置执行任何其他操作。这类似于我最近问的一个问题:这个问题还有其他一些有趣的解决方案 您可以像这样使用async的forEachLimit
var async = require("async")
var users = []; // Initialize user array or get it from DB
async.forEachLimit(users, 1, function(user, userCallback){
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'
console.log('done')
userCallback();
});
}, function(err){
console.log("User For Loop Completed");
});
for循环是一个同步工作块,它在eventloop队列上发布异步工作——那么为什么它需要以不同的顺序工作呢?也许对实际问题的澄清会给你一个更好的答案。只是不要使用
for
循环,而是使用async.map
(或任何你需要的)为什么在async
库已经可用时使用递归?个人偏好。如果异步库已经在语言级别上进行了优化,那么它的性能可能会更高(这个示例效率很低,但我更想说明递归的概念,而不是炫耀自己的能力)。由于没有深入研究该库中的代码,我很难说。我怀疑async.js是否会有更好的性能,库代码确实很糟糕,但使用它的代码会更可读。我不知道更可读,这只是一个调用来执行在数组中循环的任务。这就是说,开发人员有责任维护它,并在将来的任何更改中看到它。这绝对是使用异步库的充分理由。TBH,我不知道异步库可以在这样的数据结构级别上实现这一点。正如我前面提到的,我还没有花时间去学习它。谢谢!下面是一个后续问题: