0

我在我的节点/猫鼬应用程序中使用 async lib 并遇到了一些我不明白的问题。我得到了这段代码:

var model_1;
async.series([
    function (callback) {
        Model1.findOne( {_id: mongoose.Types.ObjectId(model1_id)}, function (err, model1) {
            if (err) {
                callaback(err);
            } else {
                model_1 = model1;
                callback();
            }
        });
    },
    function (callback) {
        async.forEach(req.body.myArray, function (element, callback) {
                model2              = new Model2();
                model2.name         = element.name;
                Model3.findOne( { _id: element.model3_id }, function (err, model3) {
                    if (err) {
                        callaback(err);
                    } else {
                        Model4.findOne( { _id: element.model4_id }, function (err, model_4) {
                            data.push({
                                    model_1:    model_1,
                                    model_2:    model_2,
                                    model_3:    model_3,
                                    model_4:    model_4,
                                });
                                callback();
                        });
                    }
                });

            }
        }, function (err) { /* callback for async.forEach */
            if (err) {
                callback(err);
            } else {
                for(var i = 0; i < data.length; i++) {
                    console.log(i+": m2 id: "+data[i].model_2._id);
                    console.log(i+": m3 id: "+data[i].model_3._id);
                    console.log(i+": m4 id: "+data[i].model_4._id);
                }
            }
        });
}], function (err) { /* callback for async.series */
    if (err) {
        next(err);
    }
});

我的 json 身体看起来像

{
    model1_id: XXXX,
    myArray: [
        {model3_id: YYYY_1, model4_id: ZZZZ_1},
        {model3_id: YYYY_2, model4_id: ZZZZ_2},
        { ... }
    ]
}

我得到的问题是,在我打印数据时的 async.forEach 回调中,model_2.id 对于所有元素都是相同的,model_3 和 model_4 ids 与 myArray 中的相同,但是我在所有位置上都得到了相同的 model_2 对象在数据变量中。如何解决这个问题?我可以将 model_2 传递给我的 find 调用吗?

4

1 回答 1

0

在 async.forEach() 的回调中不使用“var”来执行此操作会使 model2 全局化:

model2 = new Model2();

async.forEach() 并行处理 req.body.myArray 中的条目(不是系列),因此它非常快速地循环遍历所有条目,而无需等待 Model3.findOne() 完成并将数据推送到数组中。这就是为什么你会为 model2 获得相同的价值。您需要在 model2 前面添加“var”,如下所示,以便循环的每次迭代都有自己的 model2 副本,因此在循环 req.body.myArray 时不会被覆盖:

var model2 = new Model2();

另一种选择是使用 async.eachSeries() 串行处理 req.body.myArray ,这样 model2 就不会被覆盖。

于 2014-07-10T13:38:36.117 回答