如何使用Promise.all解构动态数量的异步调用的结果 [英] How to destructure results of a dynamic number of async calls with Promise.all

查看:526
本文介绍了如何使用Promise.all解构动态数量的异步调用的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过 Promise.all 并行进行未知数量的异步调用。类似于以下内容:

I need to make an unknown number of async calls in parallel via Promise.all. Something similar to this:

let externalCalls = [call1()];
if (someCondition1) {
  externalCalls.push(call2());
}
if (someCondition2) {
  externalCalls.push(call3());
}

然后 externalCalls 传递给 Promise.all ,以便它们可以并行运行。

Then externalCalls will be passed to Promise.all so they can be run in parallel.

理想情况下,我想使用解构结果,以便我可以按名称引用结果,即

Ideally, I'd like to use destructuring of the results so that I can refer to results by name, i.e.

const [call1, call2, call3] = await Promise.all(externalCalls);

我知道 call1 将会一直存在,但我不知道 call2 call3 是否会在那里。因此,我想定义动态调用 await Promise.all const 结果以具有正确的属性Is这可能吗?还是我陷入了一个未知长度的通用结果数组,然后不得不检查结果中的每个项目以查看哪个调用产生了它的问题?

I know call1 will always be there, but I don't know if call2 or call3 will be there. So I'd like to define the const result of calling await Promise.all dynamically to have the correct properties, Is this possible? Or am I stuck having a generic results array of unknown length, and then having to inspect each item in the results to see which call produced it?

推荐答案

一方面,您已经知道哪些呼叫被 .push()转换为 externalCalls ,基于 someCondition1 等。

On the one hand, you already know which calls were .push()ed to externalCalls, based on someCondition1, etc.

但是构建 externalCalls 的方式不同,因此长度始终相同:

But perhaps it's better to build externalCalls in a different way so it always has the same length:

const conditions = [true, someCondition1, etc]
const calls = [call1, call2, etc]
const externalCalls = conditions.map(
  (c, i) => c ? calls[i]() : Promise.resolve(null))
const [result1, result2, etc] = await Promise.all(externalCalls)

这篇关于如何使用Promise.all解构动态数量的异步调用的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆