Simple promise with forEach
You are returning a deferred promise and that promise doesn't get resolved or rejected . Try the following:
var forEachMatch = function(matches) {var deferred = Q.defer();matches.forEach(function(match) { var messages = Message.find({'matchid': match._id}, function(err,messages) { if(err) deferred.reject(err); else deferred.resolve(match._id); });});return deferred.promise;
};
the caller will then become
forEachMatch(matches).then(id=>{ console.log("done succesffuly found"); }).catch(err=>{ console.log("not found error",err); }).done(()=>{ console.log("done") });
In your case match better to use Q.all
, which accepts array of promises or values:
var forEachMatch = function(matches) { var promises = matches.map(match => { return Message .find({'matchid': match._id}) .then(messages => [match, messages]); }); return Q.all(promises);}forEachMatch(matches) .then(results => { console.log("DONE", results); res.status(200).json({ bob, matches: matches, });});
https://github.com/kriskowal/q/wiki/API-Reference#promiseall
You never called the promise.reject
or promise.reject
methods. Also, a promise is made for asynchronous operations, which forEach isn't.
Here is a dirty fix:
var forEachMatch = function(matches) { var deferred = Q.defer(); // make the foreach asynchronous setTimeout(function() { matches.forEach(function(match) { // do stuff }); // notify end deferred.resolve(); }, 0); return deferred.promise;};// use .thenforEachMatch(matches).then(function() { console.log("DONE");});