繁体   English   中英

如何从javascript中的array.map中的异步函数返回一个值?

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

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

我想在array1.map异步,因为我有一些需要时间的进程,所以我需要使用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)
})

期望输出:数组['hi', 'hi', 'hi', 'hi']我的输出: [[object Promise], [object Promise], [object Promise], [object Promise]]

你需要使用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']

解决方案1

如果您在地图高阶函数中等待,您将获得预期的结果

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

解决方案2

如果从高阶函数参数中删除异步,您将获得预期的输出。

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

您可以使用async模块中的async.map。 async.map函数有三个参数。

  1. 迭代的数组。
  2. 要为数组中的每个项执行的函数。
  3. 在所有迭代完成后执行回调。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM