Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  157] [ 3]  / answers: 1 / hits: 24337  / 7 Years ago, sun, april 16, 2017, 12:00:00

I am trying to create a Promise.all with an array of items. So if I create it like this it works fine



Promise.all([
Query.getStuff(items[0]),
Query.getStuff(items[1])
]).then(result => console.log(result))


If I try to create the Promise.all like this, it doesn't work



Promise.all([
items.map(item => Query.getStuff(item))
]).then(result => console.log(result))


The then block is run before the Query.getStuff(item). What am I missing?


More From » promise

 Answers
22

You should be writing



Promise.all(items.map(...))


instead of



Promise.all([ items.map(...) ])


Array#map returns an array, which means that the way you wrote your code originally, you were actually passing a multidimensional array to Promise.all — as in [ [promise1, promise2, ...] ] — instead of the expected one-dimensional version [promise1, promise2, ...].




Revised Code:



Promise.all(
items.map(item => Query.getStuff(item))
).then(result => console.log(result))

[#58132] Thursday, April 13, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shannon

Total Points: 606
Total Questions: 106
Total Answers: 111

Location: Lesotho
Member since Thu, Jun 30, 2022
2 Years ago
;