alyx
alyx

Reputation: 2733

Promise.all() with map() returns undefined items in array

Trying to generate an array of random numbers:

const arr = await generateValues(20, 500);

async function generateValues(numOfValues, max){
  return await Promise.all(
    new Array(numOfValues).map(() => Math.ceil(Math.random() * max))
  );
}

const arr is returning an array of length 20 but are all undefined.

Upvotes: 1

Views: 373

Answers (2)

Rohit.007
Rohit.007

Reputation: 3502

You might not aware of map, it does not work with the blank or empty array. you have to use fill to insert at least one element.

try it.

async function generateValues(numOfValues, max){
  return await Promise.all(
    new Array(numOfValues).fill(0).map(() => Math.ceil(Math.random() * max))
  );
}
const arr = await generateValues(20, 500);

Upvotes: 1

Ben West
Ben West

Reputation: 4596

map ignores empty elements in the array, so you have to use fill first.

var arr = new Array( 20 ).fill( 0 ).map( () => { ... } )

Upvotes: 3

Related Questions