我正在尝试在NodeJS的循环中编写一个循环,我有点困惑,结果并没有给我我期望的结果 - 有时候回调会被击中两次,依此类推。我正在使用异步模块,如果有人能在下面的代码中告诉我可能出错的地方,那就太棒了。如果有更好的方法,我会感激任何提示。
it("should add some numbers", function(done){
var typed_totals = 0, i = 0;
async.each(arr1, function(value, callback1){
var j = 0;
async.each(arr2, function(element, callback2){
testFunction(function(result){
calculate(result, function(total){
typed_totals += total;
if(++j < arr2.length){
callback2();
} else if (++i <= arr1.length){
callback1();
} else {
done();
}
});
});
});
});
});
在我的情况下, testFunction()
执行http
请求并获取一些值。 calculate()
字面上只是将其中的一些加在一起。
如果有任何不清楚的地方,请发表评论,我会根据需要编辑我的问题。
答案 0 :(得分:2)
我正准备睡觉,如果您使用更详细的信息进行编辑,我明天可能会提供更具体的答案,这里是我的嵌套async.each
循环的示例。
var async = require('async');
function addNumbers(arr1, arr2, callback){
var typed_totals = 0;
async.each(arr1, iterator1, function(err){
callback(err, typed_totals);
});
function iterator1(val1, done1){
typed_totals += val1;
async.each(arr2, iterator2, function(err){
if(err){ return done1(err) };
done1(null);
});
function iterator2(val2, done2){
process.nextTick(function(){
typed_totals += val2;
done2(null);
});
};
};
};
addNumbers([1,2],[3,4], function(err, total){
console.log(err, total);
});