首页 > 解决方案 > 如何在另一个异步函数中执行代码之前等待一个循环在异步函数中完成?

问题描述

我有一个异步函数,它循环遍历需要上传的文件数组。我有另一个用于最终表单提交的功能,需要等待所有上传完成后再提交表单。

methods: {
async selectFile() {
    for (let i = 0; i < this.Form.PostFiles.length; i++) {
        const File = this.Form.PostFiles[i][0];
        await this.uploadFile(File).then(response => {

        }).catch(error => {
        })

    }
},
async uploadFile(File) {
                const FormFile = new FormData();
                FormFile.append("PostFile", File);

                await this.$axios.post('/api', FormFile).then(response => {
                    console.log("Successfully uploaded")
                }).catch(err => {
                    console.log(err.response.data.error)
                })

      },
async sendForm() {
            const FormBody = new FormData();
            FormBody.append("Name", this.Form.Name);
            FormBody.append("Description", this.Form.Description);
            // Here I need to wait for all files to upload first!
            await this.selectFile; // But this fulfills on first iteration of for loop
            // If all files uploaded then post the form
            await this.$axios.post('/api', FormBody)
      }
}

上面代码的问题在于,只要循环 in的一次迭代完成,inawait this.selectFile部分就完成了。我需要等到所有文件都上传...那么我该如何等待整个循环完成?sendForm()forselectFile()await selectFilesendForm()

看起来for循环需要被包裹起来,然后返回一个值,表明sendForm它可以继续发送表单。我只是无法理解这是如何完成的。

标签: javascriptvue.js

解决方案


如果您像这样更改您的方法,那应该可以按预期工作:

async selectFile() {
  await Promise.all(
      this.Form.PostFiles.map(async(el, i) => {
         const File = this.Form.PostFiles[i][0];
         await this.uploadFile(File)             
    })
  );
}

推荐阅读