I have a couple of global variables to tally some totals: items
and totalPrice
I initialize them WITHOUT VAR after reading about this hoisting issue, I see them correctly updated during the for loop, but then at the end they have their starting value, so I must have some other mistake.
Here's a shortened version of my code:
items = [];
totalPrice = 0;
for (let [key, val] of lineItems.entries()){
console.log("toyID " + key + ", with quantity: " + val);
Toy.findOne( { id: key }, (err, toy) => {
if (parseInt(val) > 0){
var subtotal = val * toy.price;
var thisItem = {"item": key, "qty": val, "subtotal": subtotal};
totalPrice += subtotal; // shows correctly updated price
items.push(thisItem);
console.log("items now has: ", items); // shows items
}
});
}
console.log("At the end, totalPrice has: ", totalPrice); // here this is 0
console.log("At the end, Items has: ", items); // here this is empty again
Is there another wrinkle getting in the way of those global variables keeping their updated value?