我遇到了async.each的问题,回调是在完成任务之前进行调用,我有下面的代码,得到输出为 在调用reprice 6之前执行调用reprice 7,6是我在async.each回调中构建数组的部分
called reprice :
called reprice : 2
called reprice : 3
**called reprice : 7 []**
no chnages has been made
called reprice : 6 { status: 200, msg: 'recived optimal price 4 ', data: 17.75 }
called reprice : 6 { status: 200, msg: 'recived optimal price 4 ', data: 20.99 }
这是代码
async.forEach(records, function(result, callback) {
switch (result.Pricing) {
case "PF" : // current scenrio
var pfObject = _.filter(rules, {'sub_title': 'PF'});
checkRepriceFrequency(result, pfObject[0], function (response) {
if (response.status === 200) {
// call check inventory rules
CheckInventoryRules(result, pfObject[0], function (response) {
console.log('called reprice : 6 ',response);
if (response.status === 200) {
var price = result.sales_price;
var pushData = {
price: price,
optimalPrice: response.data,
SKU: result.SKU,
_id: result._id,
frequency: pfObject[0].reprice_frequency
};
productArray.push(pushData);
}
});
} else {
console.log('err');
}
});
}
callback(null);
}, function(err) {
console.log('called reprice : 7 ',productArray);
if (!err) {
if (productArray.length > 0) {
console.log('To update Synch : ',productArray);
} else {
console.log("no chnages has been made ");
}
}
});
答案 0 :(得分:1)
呀。所以你实施async.each
有点不对劲。请参阅async.each确保每个对象都通过循环但不确保同步执行。在您的示例中,您调用了CheckInventoryRules
,它似乎在进行AJAX调用。
但是检查一下,你已经在函数结束时调用了回调(它不等待AJAX完成)。这意味着在完成AJAX调用之前,回调可能被称为表明该特定对象的处理完成的信号。
要解决此问题,您需要检查是否正在调用AJAX调用,callback(null)
之后需要调用productArray.push(pushData);
。
通常,仅在任务完成执行时调用callback
。
答案 1 :(得分:0)
你已经完全错误地实现了async.forEach。 See this
交换机中似乎存在异步呼叫,因此您必须在该异步呼叫中呼叫 callback(null)
。
async.forEach(records, function(result, callback) {
switch (result.Pricing) {
case "PF" :
var pfObject = _.filter(rules, {'sub_title': 'PF'});
checkRepriceFrequency(result, pfObject[0], function (response) {
if (response.status === 200) {
CheckInventoryRules(result, pfObject[0], function (response) {
console.log('called reprice : 6 ',response);
if (response.status === 200) {
var price = result.sales_price;
var pushData = {
price: price,
optimalPrice: response.data,
SKU: result.SKU,
_id: result._id,
frequency: pfObject[0].reprice_frequency
};
productArray.push(pushData);
callback(null);
}
//handle callback on else otherwise final callback will not get the event.
});
} else {
/*
callback(null);
Or
callback(Someerror);
*/
console.log('err');
}
});
break;
default:
callback(null);
// return false;
//break;
}
}, function(err) {
console.log('called reprice : 7 ',productArray);
if (!err) {
if (productArray.length > 0) {
console.log('To update Synch : ',productArray);
} else {
console.log("no chnages has been made ");
}
}
});