【问题标题】:Parallel promise return in order按顺序并行承诺返回
【发布时间】:2016-12-20 00:55:54
【问题描述】:

我正在 Bluebird(或必要时使用原生 Promise)中寻找一种有效的方式来运行一个并行的 promise 数组,并在它们完成后按顺序返回它们。我猜几乎像队列锁?

所以如果我有一个包含 5 个函数的数组,函数 1 可能需要 150 毫秒,函数 2 可能需要 50 毫秒,函数 3 可能需要 50 毫秒等等。所有 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 协程来完成此任务?只是在决定最有意义/最符合我上面的例子的结构时遇到了麻烦。

【问题讨论】:

    标签: promise bluebird


    【解决方案1】:

    这只是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!')
    });
    

    如果你需要知道什么时候完成,你可以.tap(一个then不会改变返回值)them through.mapbefore 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!')
    });
    

    【讨论】:

    • 嗯,所以 .tap() 只会按照我指定的顺序执行?因此,如果 fn5() 先完成,它将等到 fn1-4 完成,从而保持我的顺序?如果是这样...很好,那很容易:-p
    • tap 不会,如果你希望它像这样排序,你可以.each .tapss 而不是 .map 他们。 Promise.each([fn1(), ....], x => x.tap(...))(与 bluebird 一起使用,或与其他承诺库中的 .reduce 一起使用。
    • 这并没有真正让我得到我希望的结果?
    猜你喜欢
    • 2019-10-11
    • 2018-03-06
    • 2018-11-09
    • 2016-11-23
    • 2020-06-16
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多