Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

q

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?

like image 423
Afshin Mehrabani Avatar asked Aug 09 '13 18:08

Afshin Mehrabani


Video Answer


1 Answers

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!
});
like image 197
gustavohenke Avatar answered Oct 07 '22 15:10

gustavohenke