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

ぃ、小莉子 提交于 2019-12-20 20:19:22

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/18153410/how-to-use-q-all-with-complex-array-of-promises

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!