Javascript 理解Promise.all和Array.map()

Javascript 理解Promise.all和Array.map(),javascript,node.js,arrays,asynchronous,promise,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) => aw

我正在从多个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的
响应
,我随后映射返回的数组以从其他API获取数据
(secondApiRequest(),等等)
。现在我在想,
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)}
0:Promise{:Array(10)}
1:Promise{:Array(10)}
2:Promise{:Array(10)}
3:Promise{:Array(10)}
4:Promise{:Array(10)}
5:Promise{:Array(5)}
6:Promise{:Array(0)}
7:Promise{:Array(0)}
8:Promise{:Array(0)}
9:Promise{:Array(0)}

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

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

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

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

如果要并行发出所有请求,应将承诺数组返回到
Promise.all()

映射每个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)))
)

你能澄清一下你想在这里发生什么吗?如果
response
包含10项,是否希望调用
secondapirest
10次?如果是这样,那么与这10个api调用相关的
secondResult
应该是什么?@JamesMonger so
response
是一个对象数组。我通过
response
数组进行映射,并对
secondApiRequest
等进行其他调用,现在对于每个映射,我将向其他API调用传递一个
id
。例如
response.map(async(item)=>secondApiRequest(id))
response
数组中的每个对象获取
id
参数。这样做会使结果平坦化,并且在
secondResult
thirdResult
fourthResult
variablesThanks中不会得到预期的结果。更新。此外,我们也不知道
响应
的项目是否实际上是每个后续请求的第一个参数,在这种情况下并不重要。如果函数忽略了
,则传递该项并不重要。在您的情况下,如果您希望忽略该项,您应该执行
()=>secondapirest()
。是的,确实是向上投票