我使用async each遍历并构造一个名为coupon_bo的对象。令人惊讶的是,在processbo函数内部,我看到了一个副作用,即processbo函数只能使用coupon_bo对象的最后一个副本。
我的理解是,由于coupon_bo对于每个迭代都是本地的,所以应该有一个新的对象用于迭代。
我是不是遗漏了什么?
function hitApplyLogic(coupon_names, coupons_list, req, callback) {
async.each(coupon_names, function(coupon_name, callback) {
var coupon_bo = new coupon_objects.CouponsBO();
coupon_bo.incoming_request = req.body;
coupon_bo.incoming_request['coupon_code'] = coupon_name.cn;
coupon_bo.incoming_request['list_offers'] = true;
setTimeout(function()
{
console.log("CONSOLE-BO: " + JSON.stringify(coupon_bo));
}, 1000);
});
}发布于 2016-10-20 21:10:21
async.each不能保证按顺序运行任务。
根据documentation:
请注意,由于此函数并行地将迭代器应用于每个项目,因此不能保证迭代器函数将按顺序完成。
我不确定你所说的processbo函数是什么意思。但是对于运行的迭代器的每个实例,var coupon_bo应该是唯一的。所以应该不会有被其他代码覆盖的问题。
我也不明白为什么你要在1s之后使用setTimeout来记录coupon_bo。
我确实发现您的实现中缺少一些东西,即在迭代器async.each(coupon_names, function(coupon_name, callback) {中对callback函数的调用
如果不调用它,你将永远被困在async.each
function hitApplyLogic(coupon_names, coupons_list, req, callback) {
async.each(coupon_names, function(coupon_name, eachCallback) { //Changed callback to eachCallback to avoid confusion with the one received in hitApplyLogic
var coupon_bo = new coupon_objects.CouponsBO();
coupon_bo.incoming_request = req.body;
coupon_bo.incoming_request['coupon_code'] = coupon_name.cn;
coupon_bo.incoming_request['list_offers'] = true;
setTimeout(function()
{
console.log("CONSOLE-BO: " + JSON.stringify(coupon_bo));
eachCallback(null); // Finished doing all the work with this particular coupon_name
}, 1000);
},
, function(err) { //This function is called once all the coupon_names were processed
if(err) {
// One of the coupon_names returned an error
console.log('One of the coupon_names returned an error');
return callback(err); // Callback received in hitApplyLogic
} else {
// Everything went OK!
console.log('All coupons were constructed');
return callback(null); // Callback received in hitApplyLogic
});
}发布于 2016-10-02 01:49:03
这是你问题的解决方案,Async's each immediately prints out all elements
async.eachSeries()将一次迭代一个数组项,而async.each()将并行一次迭代所有数组项。
https://stackoverflow.com/questions/39809331
复制相似问题