Reputation: 37
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
Reputation: 199
You can use async.map from the async module. async.map function takes three arguments.
Upvotes: 0
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
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