【问题标题】:Using async/await with a for in loop使用带有 for in 循环的 async/await
【发布时间】:2021-08-13 21:45:29
【问题描述】:

我有一个名为 uploadFiles 的对象。当我运行此代码时,首先运行 console.log 然后运行 ​​for 所以我得到空数组。我该如何解决这个问题

 let orderFilesData = [];
      for (let key in uploadedFiles) {
        uploadedFiles[key].map(async (file) => {
          let id = file.id;
          const orderFile = await this.orderFileRepository.findOne(id);
          orderFile.order = order;    
          await this.orderFileRepository.save(orderFile);
          orderFilesData.push(orderFile.fileUrl);
        });
      }
console.log(orderFilesData);

【问题讨论】:

    标签: javascript node.js loops nestjs


    【解决方案1】:

    由于您没有从地图返回任何数据,请尝试使用foreach 循环。由于您使用了async 函数,因此您在orderFilesData 中设置的内容将是一组promise,您必须await 它们。最简单的解决方案是使用Promise.all 数组(console.log(Promise.all(orderFilesData)) 应该做你想做的)

    【讨论】:

      【解决方案2】:

      我怀疑问题在于Array.map 是异步的,所以即使每个保存调用前面都有await,迭代元素并调用.map 内的匿名函数也完成了以异步方式。

      尝试用简单的for 循环替换uploadedFiles[key].map,我相信它会解决问题。

      【讨论】:

        【解决方案3】:

        当 array.map 与 async 函数一起使用时,它会返回一个未运行的 Promise 列表。您必须使用Promise.All(或其他)开始该过程。

        在你的 for 循环中试试这个

         const uploadPromises = uploadedFiles[key].map(async (file) => {
               ...
          });
          await Promise.All(uploadPromises)
        

        【讨论】:

          【解决方案4】:

          uploadedFiles 似乎是一个对象,其中键的值是数组?因此,如果您致电uploadedFiles[key].map(...),您将创建一系列承诺,其中每个承诺似乎都在等待。但是由于map 的回调是异步的,实际上你并没有在等待。最简单的方法是使用 Promise.all() 等待 map 产生的承诺数组中的所有承诺。

            let orderFilesData = [];
            for (let key in uploadedFiles) {
              await Promise.all(uploadedFiles[key].map(async (file) => {
                let id = file.id;
                const orderFile = await this.orderFileRepository.findOne(id);
                orderFile.order = order;    
                await this.orderFileRepository.save(orderFile);
                orderFilesData.push(orderFile.fileUrl);
              }));
            }
           console.log(orderFilesData);
          

          但要使其正常工作,请确保周围的功能是async

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-01-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-30
            • 2020-09-24
            • 2021-02-27
            • 2019-07-16
            相关资源
            最近更新 更多