理解 Promise.all 和 Array.map()

时间:2021-04-15 17:27:32

标签: javascript node.js arrays asynchronous promise

我正在从多个 API 检索数据,这些数据将聚合到一个最终数组中,我打算在其中映射并在 UI 中显示(使用 React)。所以为了更好的上下文,我有这种场景。

首先我从主 API 中检索主要数据

const response = await getFirstData() // returns an array

const [secondResult, thirdResult, fourthResult] = await Promise.all([
 response.map(async (item) => await secondApiRequest()),
 response.map(async (item) => await thirdApiRequest()),
 response.map(async (item) => await fourthApiRequest())
])

从上面可以看出,基于来自主 API 的 response,我然后映射返回的数组以从其他 API (secondApiRequest(), etc..) 获取数据。现在我在想 secondResult, thirdResult, fourthResult 会解析为一个对象数组,因为它应该是。但是当我在 chrome 浏览器上查看日志时,我看到了这个。

0: Promise {<fulfilled>: Array(10)}
1: Promise {<fulfilled>: Array(10)}
2: Promise {<fulfilled>: Array(10)}
3: Promise {<fulfilled>: Array(10)}
4: Promise {<fulfilled>: Array(10)}
5: Promise {<fulfilled>: Array(5)}
6: Promise {<fulfilled>: Array(0)}
7: Promise {<fulfilled>: Array(0)}
8: Promise {<fulfilled>: Array(0)}
9: Promise {<fulfilled>: Array(0)}

我知道这些操作是并行运行的,但是如何让这些操作解析并返回应包含对象的最终数组。此外,实现这一目标的最有效方法是什么,因为 finalArray 最后将包含 200 多个对象,我必须在 UI 上显示这些对象。谢谢,欢迎任何帮助。

2 个答案:

答案 0 :(得分:3)

如果要并行发出所有请求,则应向 Promise.all() 返回一组 promise。

为每个 api 映射响应,并使用 Promise.all() 等待它的承诺数组,然后使用外部调用等待所有内部 Promise.all() 调用。

const response = await getFirstData() // returns an array

const [secondResult, thirdResult, fourthResult] = await Promise.all(
  [secondApiRequest, thirdApiRequest, fourthApiRequest]
    .map(api => Promise.all(response.map(api)))
)

答案 1 :(得分:0)

这允许您并行运行后续请求并在相应的变量中检索它们的结果:

"plugins": [ "inline-react-svg" ]