asynchronousnodejs中的每个variables作用域
我使用asynchronous每个循环,并构build一个名为coupon_bo
的对象。 令人惊讶的是,在processbo
函数中,我看到了只有coupon_bo
对象的最后一个副本可用于coupon_bo
函数的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); }); }
async.each
不能保证按顺序运行任务。
根据文档:
请注意,由于此函数并行地将迭代应用于每个项目,因此不能保证迭代函数将按顺序完成。
我不确定你的意思是通过processbo
function。 但是对于运行的迭代器的每个实例, var coupon_bo
应该是唯一的。 所以不应该被其他人重写。
我也不确定你为什么使用setTimeout
在1 coupon_bo
后loggingcoupon_bo
。
我在你的实现中find了一些东西,这是对iteratee中的callback
函数的调用async.each(coupon_names, function(coupon_name, 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 }); }
这是您的问题的解决scheme, asynchronous的每一个立即打印出所有元素
async.eachSeries()
将一次迭代数组项,其中async.each()
将并行迭代所有项目。