_.each()
is not asyncronous, so you'll have a hard time continue execution when all of the totals are populated. Also, if you have no control over how many orders the Order.find()
will return, you can get some serious performance problems by not throttling the population with a limit.
You can try something like this:
Order.find({}, function (err, orders) {
// populate max 15 orders at any time
async.mapLimit(orders, 15, function (order, cb) {
async.parallel({
invoice: function (cb) {
order.totalInvoiced(cb);
},
discount: function (cb) {
order.totalDiscount(cb);
}
}, function (err, result) {
order.totalInvoiced = result.invoice;
order.totalDiscount = result.discount;
return cb(null, order);
});
}, function (err, orders) {
console.log('Done!');
});
});