首页 > 解决方案 > 如何从javascript中array.map中的异步函数返回一个值?

问题描述

如何从 array.map 中的异步函数返回值我试图从它们访问值但我得到 Array [[object Promise], [object Promise], [object Promise], [object Promise]]

我想在里面异步,array1.map因为我有一些需要时间的过程,所以我需要使用等待。

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

预期输出:排列['hi', 'hi', 'hi', 'hi'] 我的输出:[[object Promise], [object Promise], [object Promise], [object Promise]]

标签: javascriptarrays

解决方案


您需要使用Promise.all函数,在其中放置一系列承诺

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

预期输出:数组 ['hi', 'hi', 'hi', 'hi']


推荐阅读