繁体   English   中英

在另一个异步 function 中执行代码之前,如何在异步 function 中等待循环完成?

[英]How to wait for a loop to finish in an async function before executing code in another async function?

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

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)
      }
}

上面代码的问题是,只要 selectFile() 中的for循环的一次迭代完成, selectFile() sendForm()中的await this.selectFile部分就完成了。 我需要等到所有文件都上传......所以我怎样才能让sendForm()中的await selectFile等待整个循环完成?

似乎for循环需要包装在某些东西中,然后返回一个值,指示sendForm可以提前 go 并发送表单。 我只是无法理解这是如何完成的。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM