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

Afshin Mehrabani picture Afshin Mehrabani · Aug 9, 2013 · Viewed 19.1k times · Source

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?

Answer

gustavohenke picture gustavohenke · Aug 9, 2013

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!
});