簡體   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