我正在尝试创建一个包含项目数组的Promise.all
。所以如果我像这样创建它,它可以正常工作
Promise.all([
Query.getStuff(items[0]),
Query.getStuff(items[1])
]).then(result => console.log(result))
如果我尝试像这样创建Promise.all
,它不起作用
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(...) ])
Array#map
返回一个数组,这意味着您最初编写代码的方式实际上是将多维数组传递给Promise.all
- 如[ [promise1, promise2, ...] ]
- 而不是预期的一维版本[promise1, promise2, ...]
。
修订后的守则:
Promise.all(
items.map(item => Query.getStuff(item))
).then(result => console.log(result))