如何在JavaScript中使用“Promise.all”中的“Array”和“map”
我正在尝试创建一个带有项目数组的如何在JavaScript中使用“Promise.all”中的“Array”和“map”,javascript,promise,Javascript,Promise,我正在尝试创建一个带有项目数组的承诺。因此,如果我像这样创建它,它工作得很好 Promise.all([ Query.getStuff(items[0]), Query.getStuff(items[1]) ]).then(result => console.log(result)) 如果我尝试创建承诺。所有的都是这样,它就不起作用了 Promise.all([ items.map(item => Query.getStuff(item)) ]).then(resu
承诺。因此,如果我像这样创建它,它工作得很好
Promise.all([
Query.getStuff(items[0]),
Query.getStuff(items[1])
]).then(result => console.log(result))
如果我尝试创建承诺。所有的都是这样,它就不起作用了
Promise.all([
items.map(item => Query.getStuff(item))
]).then(result => console.log(result))
then
块在Query.getStuff(item)
之前运行。我遗漏了什么?你应该在写
Promise.all(items.map(...))
而不是
Promise.all([ items.map(...) ])
返回一个数组,这意味着您最初编写代码的方式实际上是将多维数组传递给Promise.all
-如[[promise1,promise2,…]
-而不是预期的一维版本[promise1,promise2,…]
。
修订守则:
结果是什么。它是一个数组吗?是@Gilboot结果是一个与提供的数组顺序相同的数组const resultArray=wait Promise.all(items.map(…)
Promise.all(
items.map(item => Query.getStuff(item))
).then(result => console.log(result))