并行处理承诺

问题描述 投票:1回答:3

我从我的客户服务获得了套接字连接,并接收了一组数据。基于数组中的每个元素,我将创建查询并将其发送到数据库。我如何异步解决此承诺?

Promise.all([p1, p2, p3, ...)

全部承诺对我没有用,因为我需要解决任何一个问题之后发出的事件。

每次这些承诺中的任何一项都得到解决,我应该做一些工作。

所以我想知道每个诺言是否有办法接收事件?

javascript promise rxjs
3个回答
1
投票

您可以简单地在promise数组上循环,并将.then处理程序附加到所有它们,像这样

const promises = [p1, p2, p3, ...]
for (const promise of promises) {
    promise.then(() => console.log('done'));
}

0
投票

如果您想要:

  1. 然后并行运行。
  2. 在每个诺言完成时做点什么
  3. 知道它们什么时候完成

您可以这样做:

Promise.all([
    p1.then(result => { /* do something when p1 is done; return result; */}),
    p2.then(result => { /* do something when p2 is done; return result; */}),
    p3.then(result => { /* do something when p3 is done; return result; */}),
]).then(allResults => {
    console.log("all promises done");
}).catch(err => {
    console.log(err);
});

[如果您想知道它们何时全部完成,即使其中一些出现错误:

Promise.allSettled([
    p1.then(result => { /* do something when p1 is done; return result; */}),
    p2.then(result => { /* do something when p2 is done; return result; */}),
    p3.then(result => { /* do something when p3 is done; return result; */}),
]).then(settledResults => {
    console.log("all promises done");
});

现在,通常不会在这样的单独变量中包含p1p2p3。通常,您只需要像这样直接调用函数即可:

Promise.all([
    fn1(arg1).then(result => { /* do something when fn1 is done; return result; */}),
    fn2(arg2).then(result => { /* do something when fn2 is done; return result; */}),
    fn3(arg3).then(result => { /* do something when fn3 is done; return result; */}),
]).then(allResults => {
    console.log("all promises done");
}).catch(err => {
    console.log(err);
});

0
投票

rxjs解决方案是使用merge

merge(from(p1),from(p2),from(p3))
.subscribe(()=>{.. will execute when any one of promise complete})
© www.soinside.com 2019 - 2024. All rights reserved.