如何在JavaScript中的`Promise.all`中使用`Array#map`

jha*_*amm 11 javascript promise

我正在尝试Promise.all使用一系列项目创建一个.所以,如果我像这样创建它,它工作正常

Promise.all([
  Query.getStuff(items[0]),
  Query.getStuff(items[1])
]).then(result => console.log(result))
Run Code Online (Sandbox Code Playgroud)

如果我尝试创建Promise.all这样的,它不起作用

Promise.all([
    items.map(item => Query.getStuff(item))
]).then(result => console.log(result))
Run Code Online (Sandbox Code Playgroud)

then块在之前运行Query.getStuff(item).我错过了什么?

gyr*_*yre 26

你应该写作

Promise.all(items.map(...))
Run Code Online (Sandbox Code Playgroud)

代替

Promise.all([ items.map(...) ])
Run Code Online (Sandbox Code Playgroud)

Array#map返回一个数组,这意味着你最初写代码的方式,你实际上是传递一个多维数组Promise.all-为 [ [promise1, promise2, ...] ]-而不是预期的一维版本[promise1, promise2, ...].


修订代码:

Promise.all(
    items.map(item => Query.getStuff(item))
).then(result => console.log(result))
Run Code Online (Sandbox Code Playgroud)