I am coding with Nodejs, MongoDB and Express. The code below looks for an user object with specific id in MongoDB. Once the user object is found, it retrieves favorite property of that object. The favorite property is an array whose each element is _id of a product. I tries to loop through this array. With each loop, I try to retrieve a product object from MongoDB and append this product object to new array (in my code below it's called "list"). I put some console.log() to check value of the list. It has value with each loop, but finally when I get the final one, it has null. I know the problem happens because I don't use properly deferred.resolve and deferred.promise. Please help me and explain deferred.resolve and deferred.promise works in the code. Thank you very much
function showBasket(user) {
var deferred = Q.defer();
var list =[];
db.users.findById(user, function (err, user) {
if (err) deferred.reject(err);
if (user) {
var favorite = user.favorite;
favorite.forEach(function(e){
db.products.findById(mongo.helper.toObjectID(e), function(err, product){
if (err) deferred.reject(err);
if (product) {
list.push(product);
console.log(list);// list has value here
}
})//end db.products.findById
})//end of forEach
} //end of if
console.log(list);// But finally, list has null value here
deferred.resolve(list);
});//end of db.users.findById
return deferred.promise;
}
db.products.findByIdasynchronous? If so,listis being tested and the deferred being resolved before any of the call backs requested in the.forEachfunction have been made. The callbacks push a product ontolist, but this is some time later, after you logged list and found it to be empty.