I need to iterate in an array looking for items and then sum those prices.
It's a problem of asynchronous functions. I'm using Q to help me with promises, but I can't solve this situation.
var price = 0;
var setPrice = function() {
_.each(order.items, function(item) {
Item.findOne({ 'shortname': item.item }).exec().then(function(doc) {
price += doc.price;
});
});
}
Q.nfcall(setPrice).then(function() {
console.log(price);
}
Price is set to 0, nfcall runs the setPrice function that iterate and sum prices and then, the "then" function should show the total price, but it doesn't.
How can I solve this situation?
Instead of trying to find them one by one, why not return all of them at once.
Item.where('shortname'.in(order.items).execute(function(err,docs) {
//in here you can do your summation, and the rest of your code.
var price = 0;
for(var i=0;i<docs.length;i++) {
price += docs[i].price;
}
});