0

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

3 Answers 3

1

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']

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thank you solution1 works for my case because I have some async functions inside the array.map.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.