for循环

时间:2015-06-24 20:23:50

标签: node.js mongodb

function ParseOrderSchema(CartItems , callback)
{
    var lookup = 0;
    var subOrderList = new Array();

    for(var i=0;i<CartItems.length;i++)
    {
        Meal.findOne({ _id: CartItems[i].id }).lean().exec(function (err, meal) {

            console.log(CartItems[i]);
            //meal.mealQTY = CartItems[i].qty;
            var s = new subOrder({ meals: meal, deliveryDate: getMomentDate(0) });
            subOrderList.push(s);

            if (++lookup == CartItems.length) callback(subOrderList);
        });
    }
}

CartItem[i].id它工作正常并且能够正常工作。但它在meal.mealQTY = CartItems[i].qty;

这一行失败了

它无法识别CartItems[i]方法中的findOne()

1 个答案:

答案 0 :(得分:2)

由于findOne是异步的,i在回调中始终为CartItems.length,因为for循环在任何findOne回调发生之前运行完成

您可以通过使用forEach迭代CartItems来解决此问题,以便在本地函数参数中捕获每个迭代的元素:

function ParseOrderSchema(CartItems, callback) {
    var lookup = 0;
    var subOrderList = new Array();

    CartItems.forEach(function(cartItem) {
        Meal.findOne({ _id: cartItem.id }).lean().exec(function (err, meal) {

            console.log(cartItem);
            meal.mealQTY = cartItem.qty;
            var s = new subOrder({ meals: meal, deliveryDate: getMomentDate(0) });
            subOrderList.push(s);

            if (++lookup == CartItems.length) callback(subOrderList);
        });
    });
}