Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use `Array#map` within `Promise.all` in JavaScript

Tags:

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?

like image 223
jhamm Avatar asked Apr 16 '17 06:04

jhamm


People also ask

How do we use array?

An array is a data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

What is an array with example?

An array is a collection of similar types of data. For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names. String[] array = new String[100];

What is the main use of array?

The purpose of an array is to store multiple pieces of data of the same type together.


1 Answers

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)) 
like image 189
gyre Avatar answered Sep 17 '22 09:09

gyre