简体   繁体   中英

How to use Q.all() with complex array of promises?

Consider I have an array of objects and promises, something like:

[{
    a: 1
}, {
    a: 4
}, {
    a: 4
}, {
    promiseSend: [Function],
    valueOf: [Function]
}, {
    promiseSend: [Function],
    valueOf: [Function]
}]

Now when call I Q.all(arr) and return the object value in then() , nothing's happen and still my array contains promise objects. Is there any way to work with the Q.all() and such a complex arrays?

That's how Q is supposed to work.
To get all the values, not the promises, you may use .spread() :

Q.all([a, b]).spread(function (a, b) {
    return a + b;
});

Each argument of the spread() callback will be the result of each promise, in its order.

If you think you'll have lots of promises in such array, loop thru the argument provided in then() and replace the promises with its value:

Q.all(promises).then(function(result) {
    for (var i = 0, len = result.length; i < len; i++) {
        if (Q.isPromise(result[i])) {
            result[i] = result[i].valueOf();
        }
    }

    // Next step!
});

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