在nodejs中同步每个变量范围

时间:2016-10-01 17:07:13

标签: node.js asynchronous node-async

我使用异步来循环并构建一个名为coupon_bo的对象。令人惊讶的是在processbo函数内部,我看到了一个副作用,其中只有coupon_bo对象的最后一个副本可用于processbo函数。

我的理解是,由于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);
    });
}

2 个答案:

答案 0 :(得分:1)

async.each has no guarantee of running the tasks in order.

Per the documentation:

Note, that since this function applies iteratee to each item in parallel, there is no guarantee that the iteratee functions will complete in order.

I'm not sure what you meant by processbo function. But var coupon_bo should be unique to each instance of the iteratee that is ran. So there should be no issue of it being overwritten by the other ones.

I'm also not sure why you're using setTimeout to log coupon_bo after 1s.

I did find something missing in your implementation which is the call to the callback function in the iteratee async.each(coupon_names, function(coupon_name, callback) {

Without calling it you'll be forever stuck at 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
        });
}

答案 1 :(得分:0)

以下是您的问题的解决方案Async's each immediately prints out all elements

async.eachSeries()将一次迭代数组第一项,其中async.each()将同时迭代所有项目。