并行承诺按顺序返回

时间:2016-12-19 16:35:47

标签: promise bluebird

我正在寻找Bluebird(或必要时的本机Promise)的有效方法来运行并行的promises数组,并在完成后按顺序返回它们。我猜这几乎就像一个队列锁?

因此,如果我有一个包含5个函数的数组,函数1可能需要150ms,函数2可能需要50ms,函数3可能需要50ms等。所有5个函数都是并行调用但返回值的回调只会按顺序响应我说明了。理想情况下是这样的:

Promise.parallelLock([
    fn1(),
    fn2(),
    fn3(),
    fn4(),
    fn5()
])
.on('ready', (index, result) => {
    console.log(index, result);
})
.then(() => {
    console.log('Processed all');
})
.catch(() => {
    console.warn('Oops error!')
});

我想我可以用Bluebird协程来完成这个任务吗?只是难以确定最有意义的结构/与我上面的例子最相符。

1 个答案:

答案 0 :(得分:3)

那只是等待所有承诺的Promise.all,承诺就像一个价值 - 如果你有一个承诺已经执行了行动:

Promise.all([
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1()
])
.then(results => {
    // this is an array of values, can process them in-order here
    console.log('Processed all');
})
.catch(() => {
    console.warn('Oops error!')
});

如果您需要知道何时完成,可以.tapthen不会更改返回值)them through。map before passing them to。all `:

Promise.all([
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1(),
    fn1()
].map((x, i) => x.tap(v => console.log("Processed", v, i))
.then(results => {
    // this is an array of values, can process them in-order here
    console.log('Processed all');
})
.catch(() => {
    console.warn('Oops error!')
});