Reputation: 121
I'm trying to pull inventory data from the db, loop each row and fetch the item name.
I'm not used yet to callback shenanigans and this has stumped me. How can I loop all the items, start a callback to fetch all the names and once everything is ready, call the next function?
I have a feeling it's either really close to what I have, or it's impossible the way I designed it.
Inventory.getPlayerInventory = function(playerId, next){
Inventory
.find({playerId: playerId})
.select('itemId quantity')
.exec( function getPlayerInventoryExec(err, inventories){
_.each(inventories, function getPlayerInventoryEach(inventory, index){
projectv.class.item.findById(inventory.itemId, function getPlayerInventoryFindById(err,item){
inventories[index].itemName = item.itemName;
})
});
next(err, inventories);
});
};
Upvotes: 0
Views: 92
Reputation: 259
I think using async will help you a lot here. Try something like this:
Inventory.getPlayerInventory = function(playerId, next){
Inventory
.find({playerId: playerId})
.select('itemId quantity')
.exec( function getPlayerInventoryExec(err, inventories){
async.eachSeries(inventories, function (inventory, each_done){
projectv.class.item.findById(inventory.itemId, function getPlayerInventoryFindById(err,item){
if (err) return each_done(err);
inventories[index].itemName = item.itemName;
each_done();
});
},
function(err){
// called after we're done iterating over the collection
next(err, inventories);
});
});
This will ensure each findById() query will have time to complete before moving on to the next item (by calling each_done()). More information is available here.
Upvotes: 1