chaitanya ivvala
chaitanya ivvala

Reputation: 37

How to return a value from a async function in array.map in javascript?

how to return the value from an async function in the array.map I am trying to access the value from them but I am getting Array [[object Promise], [object Promise], [object Promise], [object Promise]]?

I want async inside the array1.map because I have some process that takes time so I need to use await.

var array1 = [1, 4, 9, 16];

// pass a function to map
const test = async ()=>{
const map1 = await array1.map(async x => 'hi');

return map1;
// expected output: Array [2, 8, 18, 32]
}
test().then((data)=>{
console.log(data)
})

expected output: Array ['hi', 'hi', 'hi', 'hi'] my output: [[object Promise], [object Promise], [object Promise], [object Promise]]

Upvotes: 0

Views: 653

Answers (3)

Swarup Bam
Swarup Bam

Reputation: 199

You can use async.map from the async module. async.map function takes three arguments.

  1. Array to iterate over.
  2. Function to be executed for each item from the array.
  3. Callback to be executed after all iterations are done.

Upvotes: 0

Alex Varghese
Alex Varghese

Reputation: 2230

Solution 1

If you put await inside the map higher order function you will get expected result

var array1 = [1, 4, 9, 16];

// pass a function to map
const test = async () => {
  const map1 = await Promise.all(array1.map( async x =>await  'hi'));
  return map1;
}

test().then((data) => {
  console.log(data)
});

Solution 2

If you remove async from the higher order function parameter you will get the expected output .

var array1 = [1, 4, 9, 16];

// pass a function to map
const test = async () => {
  const map1 = await Promise.all(array1.map( x => 'hi'));
  return map1;
}

test().then((data) => {
  console.log(data)
});

Upvotes: 0

Alex
Alex

Reputation: 1423

You need to use Promise.all function, where you put your array of promises

var array1 = [1, 4, 9, 16];

// pass a function to map
const test = async () => {
  const map1 = await Promise.all(array1.map(async x => 'hi'));
  return map1;
}

test().then((data) => {
  console.log(data)
});

expected output: Array ['hi', 'hi', 'hi', 'hi']

Upvotes: 1

Related Questions