JavaScript、异步/等待和 promise

标签 javascript async-await

我对 async/await 和一些 Promise 有疑问。

我有这个代码。它从这里开始:

let valid = await LoadRouter.load(body);
console.log(valid);//showing me Pending Promises

功能是:

loadGeneratingUnits(data){
   let newUGArray = [];
   try {
     const result =  data.map(async (itemGU, index) => {
        const checGU = await this.checkDataGu(itemGU.nombre);
        if(!checGU){
           let newUG = {
              generating_unit_name: itemGU.nombre,
              description: (!itemGU.descripcion) ? null : itemGU.descripcion,
              it_generating_unit_id: (!itemGU.it_unidad_generadora) ? 0 : itemGU.it_unidad_generadora
           }
           newUGArray.push(newUG);
        }
     }) 

     return result;

   } catch (error) {
      throw new Error(error.message)

   }
}

这就是我遇到问题的地方

async checkDataGu(guName = null){
  if(guName){
      return await generatingUnitModel.findOne({
         attributes: [
            'id',
            'generating_unit_name',
         ],
          where: {
              generating_unit_name: guName

          }
      })
  }

}

关于在此代码上使用 async/await 有什么评论吗?

最佳答案

通过异步回调 data.map()data.map() 现在将数据转换为 Promises 数组,因为异步函数的返回值始终是一个 Promise。 await 只会等待 Promise 解析,而不是等待 Promise 的数组。您应该使用 Promise.all 来实现:

 const result =  Promise.all(data.map(async (itemGU, index) => {
    const checGU = await this.checkDataGu(itemGU.nombre);
    if(!checGU){
       let newUG = {
          generating_unit_name: itemGU.nombre,
          description: (!itemGU.descripcion) ? null : itemGU.descripcion,
          it_generating_unit_id: (!itemGU.it_unidad_generadora) ? 0 : itemGU.it_unidad_generadora
       }
       newUGArray.push(newUG);
    }
 }))

现在结果一个 Promise,它将使用每个内部 Promise 解析的值数组进行解析。最终,这意味着您的上层 let valid = wait LoadRouter.load(body); 应使用您期望的数组进行解析。

关于JavaScript、异步/等待和 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59619117/

相关文章:

c# - 对 c# 的 async/await 的控制流感到困惑

C# HttpClient 跟踪卡住

javascript - Node.js 在 mysql 中使用异步/等待

JavaScript 添加事件监听器

javascript - Backbone : Best way to handle large amounts of view listeners?

javascript - 从 URL 获取值(value)

javascript - 如何在全局和 Element 原型(prototype)中使用 JavaScript 函数?

reactjs - 如何等待 forEach 循环完成

c# - 如何使用单个 'await Task.WhenAll' 简化多个等待?

javascript - 如何在机器人回复建议操作时隐藏/显示发送箱