admin管理员组

文章数量:1178543

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?

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?

Share Improve this question edited Apr 16, 2017 at 7:09 gyre 16.8k4 gold badges40 silver badges47 bronze badges asked Apr 16, 2017 at 6:31 jhammjhamm 25k42 gold badges110 silver badges187 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 39

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))

本文标签: How to use Arraymap within Promiseall in JavaScriptStack Overflow