Im putting together a Node.js app just for fun, and while I have an api fully cruddy, I still have some small stuff to iron out.
Atm I have this:
[php]function addItemsToUsersAsync(users, callback) {
var itemModel = mongoose.model(‘items’);
users.forEach(function(user) {
itemModel.find({user_id: user.id}).exec(function(err, items) {
if (!err) {
user.items = items;
}
});
});
callback(users);
}[/php]
Not sure how I can get this working as the callback placed after the loop will return an unmodified array of objects, but if I do the callback inside the find function like this:
[php]function addItemsToUsersAsync(users, callback) {
var itemModel = mongoose.model(‘items’);
var i = 1;
users.forEach(function(user) {
i++;
itemModel.find({user_id: user.id}).exec(function(err, items) {
if (!err) {
user.items = items;
if (i > 10) {
callback(users);
}
}
});
});
}[/php]
it works just fine.
How can I do the callback after the loop, correctly/clean?