Javascript 并行执行多个承诺,但仅从其中一个承诺中检索结果

Javascript 并行执行多个承诺,但仅从其中一个承诺中检索结果,javascript,typescript,concurrency,promise,Javascript,Typescript,Concurrency,Promise,我目前有一个程序,我想并行调用几个restapi:s,但我只对其中一个的结果感兴趣 目前我已经这样解决了: private async loadData () { const all = [this.loadFirstData(), this.loadSecondData(), this.loadThirdData()]; const combine = Promise.all(all); await combine; // One of the promise

我目前有一个程序,我想并行调用几个restapi:s,但我只对其中一个的结果感兴趣

目前我已经这样解决了:

private async loadData () {
    const all = [this.loadFirstData(), this.loadSecondData(), this.loadThirdData()];
    const combine = Promise.all(all);
    await combine;

    // One of the promises just puts it's return value in this global variable, so that I can access it after it is done.
    if (this.valueFromThirdAPI) {
        // Do something with value
    }
}
所以我要做的就是把我想要的承诺的结果放在一个全局变量中,在所有承诺都返回后,我可以访问这个全局变量。这是可行的,但我相信一定有更好的方法

承诺。all
返回一个解析值数组,但如果我只对其中一个值感兴趣,如何区分它们?另外两个不需要归还任何东西


提前谢谢

Promise.all
返回一个与给定Promise顺序相同的数组:

private async loadData () {
    const all = [this.loadFirstData(), this.loadSecondData(), this.loadThirdData()];
    const combine = Promise.all(all);
    const values = await combine;

    // One of the promises just puts it's return value in this global variable, so that I can access it after it is done.
    if (values[2]) {
        // Do something with value
    }
}

当返回值全部解析后,可以对其进行迭代。 Promise.all().then(值)
首先看一看,等待承诺是有道理的

您可以使用返回的数组索引访问结果。 另一个选项是使用数组析构函数

下面是一个例子

const promise1=Promise.resolve(1);
const promise2=承诺。解决(2);
const promise3=Promise.resolve('this one');
const promise4=承诺。解决(4);
异步函数测试(){
//请注意双“,”以忽略前两个承诺。
const[,三]=等待承诺。全部([promise1,promise2,promise3,promise4]);
控制台日志(三个);
}

test()等待第三个,然后等待全部。因此,如果第三个在第一个和第二个之前完成,您可以更早地处理它

private async loadData () {
    const all = [this.loadFirstData(), this.loadSecondData(), this.loadThirdData()];
    const third = await all[2];
    if (third) {
        // Do something with value
    }

    await Promise.all(all);
}

也可能是一个想法->
const combine=wait Promise.all(all)
并删除
等待组合
,否则
组合
仍将是承诺。是的,但我只是想尽可能少地更改,以便OP看到正在发生的事情。也许,但上述操作不起作用,组合是承诺而不是数组。远离
异步/等待
,对thenables来说似乎是一个倒退,你不认为吗?也许,async/await很好,但thenables仍然可以工作。如果你想要第三个的早期过程,这是一个好主意,。但有一件事需要注意。如果1和2失败,第三个仍然可以得到处理,所以即使您可能对1和2的结果不感兴趣,您仍然可能要求它们成功。IOW:只要你不在乎1和2失败,这是个好主意。是的,正如@Keith所说,我需要在使用第三个承诺的结果之前完成所有这些。但很高兴知道这也是可能的!我想这是最干净的了。谢谢