var deferred = Q.defer(); … deferred.resolve(…); … deferred.resolve(…);
call()
is a shorthand for exporting promises
That will not work! You need to create a new deferred for each promise that you want. However, you shouldn't use Deferred
s anyway! Instead, use the many Node callback helper functions.
As you can see, the callback of .each is executed later than pushing promises to array. I believe it can be made by using result.toArray() instead of .each, but how can it be done with the help of .each loop?
It cannot, unless you know beforehand how often each
will be called and how many promises will need to be created. Q.all
is a bit useless in here, since the promises are not created at once and execute their tasks in parallel - instead, they are a stream.
You really should use toArray
here, to get a single callback with which you resolve the promise.
Well, there is a way, but it's ugly and less efficient than toArray
. You can have one deferred that will always wait, and is only resolved with a promise for the rest of the stream.
function loop(result) {
var deferred = Q.defer();
result.each(function (err,data){
if (err) {
deferred.reject(err);
} else if (data == null) {
deferred.resolve([]); // end of the stream
} else {
var nextDeferred = Q.defer();
deferred.resolve(nextDeferred.promise.then(function(rest) {
return [data].concat(rest);
}));
deferred = nextDeferred;
}
})
return deferred.promise;
}