简体   繁体   中英

Q.all is not working

I have a problem with my node.js e2e test. I want to wait for 2 promises to resolve. But for some reason when I use Q.all it is just freezing my app. I am using kriskowal's Q 1.0.0.

This works:

var doStuff = function() {
    var promiseA = getPromiseA();
    return promiseA;
}


var prepareTestData = function(done) {
    doSomething()
    .then(doStuff)
    .then(done);
}

But this does not:

var doStuff = function() {
    var promiseA = getPromiseA();
    var promiseB = getPromiseB();
    return [promiseA, promiseB];
}


var prepareTestData = function(done) {
    doSomething()
    .all(doStuff)
    .then(done);
}

Can someone help me out what I am missing?

* Updated *

The simplified answer to your question is that the all() prototype method doesn't take parameters, so .all(doStuff) is only calling .all() on the promise returned by doSomething() and doStuff ends up being an argument that's never used. The simplest solution is to use nikc.org's solution.

There are two ways to use .all() in Q.

One is to use Q.all() on an array of promises to create a promise whose result is an array of all the resolutions of those promises.

var doStuff = function() {
    var promiseA = getPromiseA();
    var promiseB = getPromiseB();
    return Q.all([promiseA, promiseB]);
}


var prepareTestData = function(done) {
    doSomething()
    .then(doStuff)     // use then here
    .then(done);
}

The other (as shown in nikc.org's answer) is to call .all() on a promise whose result is an array of promises. This will produce a new promise whose result is an array of the resolutions of all those promises:

var doStuff = function() {
    var promiseA = getPromiseA();
    var promiseB = getPromiseB();
    return [promiseA, promiseB];
}


var prepareTestData = function(done) {
    doSomething()
    .then(doStuff)
    .all()
    .then(done);
}

In both cases, the result passsed to done will be an array with the resolved values of promiseA and promiseB .

The call to Promise.all should be after calling doStuff which is returning the array of promises. Alternatively, you return Q.all(Array) from doStuff .

var prepareTestData = function(done) {
    doSomething()
    .then(doStuff) // array returned here
    .all()         // all creates a promise of promises
    .then(done);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM