簡體   English   中英

在 Javascript 數組映射中使用 promise 函數

[英]Using promise function inside Javascript Array map

有一個對象數組 [obj1, obj2]

我想使用 Map 函數對所有這些進行數據庫查詢(使用承諾)並將查詢結果附加到每個對象。

[obj1, obj2].map(function(obj){
  db.query('obj1.id').then(function(results){
     obj1.rows = results
     return obj1
  })
})

當然這不起作用,輸出數組是 [undefined, undefined]

解決此類問題的最佳方法是什么? 我不介意使用其他庫,例如 async

將您的數組映射到 Promise,然后您可以使用Promise.all()函數:

var promises = [obj1, obj2].map(function(obj){
  return db.query('obj1.id').then(function(results){
     obj1.rows = results
     return obj1
  })
})
Promise.all(promises).then(function(results) {
    console.log(results)
})

您沒有在map函數中返回您的 Promises。

[obj1, obj2].map(function(obj){
  return db.query('obj1.id').then(function(results){
     obj1.rows = results
     return obj1
  })
})

使用異步/等待的示例:

const mappedArray = await Promise.all(
  array.map(p => {
    return getPromise(p).then(i => i.Item);
  })
);

您也可以for await代替map ,並在其中解決您的承諾。

您還可以使用p-map 庫來處理 map 函數中的 Promise。

當您需要同時使用不同的輸入多次運行 promise-returning 和 async 函數時很有用。

這與 Promise.all() 的不同之處在於您可以控制並發並決定是否在出現錯誤時停止迭代。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM