2
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);
        });
    }
}

At CartItem[i].id it works fine and is able to work fine. But it fails at this line meal.mealQTY = CartItems[i].qty;

It can't recognize CartItems[i] inside the findOne() method.

3
  • Can you show us the Meal schema? Commented Jun 24, 2015 at 20:33
  • It is a simple schema with meal name and quantity Commented Jun 24, 2015 at 20:34
  • And is there any way to resolve this ? Commented Jun 24, 2015 at 20:44

1 Answer 1

3

Because findOne is async, i will always be CartItems.length inside the callback as the for loop runs to completion before any of the findOne callbacks occur.

You can fix this by iterating over CartItems using forEach instead so that each iteration's element is captured in a local function parameter:

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);
        });
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works Thank You. Moving from Sync prog. to Async seems more challenging than previously anticipated :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.