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]]
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']
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加