How does Q.all work in NodeJS?

I have the following code:

var a = [1,2,3,4,5];
var promises = [];
a.forEach(function(item,index){
    var deferred = Q.defer();
    doSomething().then(function(){
        deferred.resolve(true);
        promises.push(deferred);
    });
});

Q.all(promises).then(function(data){
    console.log("something!!");
});

      

How does Q.all know that the promises array has all the promises needed for the forEach loop? Sometimes my Q.all works before forEach. Please tell me where I am wrong.

doSomething () is an asynchronous function that returns a promise.

+3


source to share


2 answers


Q.all

cannot work before yours forEach

, as it forEach

is synchronous.

But you are actually pushing things in the array after the call to Q.all. Your way of using promises is a little awkward: you don't need to use a promise!

Also, you don't want to push the hyphen out of itself, but rather the promise it has after being rejected or allowed. See below for more information on how to "promise" an asynchronous function.

Deffered are used to define promises outside of callback based simplex asynchronous code. Since it doSomething()

returns a promise (you are using .then()

), you could simply do:

var a = [1,2,3,4,5];
var promises = [];
a.forEach(function(item,index){
    var promise = doSomething().then(function(data){
        return Q(true);
    });
    promises.push(promise);
});

Q.all(promises).then(function(data){
    console.log("something!!");
});

      

The promises will then be directly populated by the promises without any delay.



EDIT: Since you're asking about doSomething

non-promise, here's what you could do:

Let's say it doSomething

takes as a parameter a callback to execute after some asynchronous task.

Then you can wrap doSomething

like this:

function doSomethingPromise(){
    var defered = Q.defer();
    doSomething(function(err,data){
       if(err){
           defered.reject(err);
       }
       else{
           defered.resolve(data);
       }
    });
    return defered.promise;
}

      

and then use doSomethingPromise()

as above instead doSomething

, as this returns a promise.

+6


source


The problem is that the Q.all

array promises

is still empty when executed . Deferred objects are pushed to promises

asynchronously, so Q.all()

will execute until the promise from is resolved doSomething()

.



+2


source







All Articles