简体   繁体   English

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

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

I have an async function which loops through an array of files that need to be uploaded.我有一个异步 function 循环遍历需要上传的文件数组。 I have another function for a final form submit that needs to wait for ALL the uploads to have finished before submitting the form.我还有另一个 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)
      }
}

The problem with the code above is that the await this.selectFile part in sendForm() is fulfilled as soon as only one iteration of the for loop in selectFile() completes.上面代码的问题是,只要 selectFile() 中的for循环的一次迭代完成, selectFile() sendForm()中的await this.selectFile部分就完成了。 I need to wait until all the files are uploaded... so how can I make await selectFile in sendForm() wait for the entire loop to complete?我需要等到所有文件都上传......所以我怎样才能让sendForm()中的await selectFile等待整个循环完成?

It seems like the for loop needs to be wrapped in something, and then returns a value indicating to sendForm that it can go ahead and send the form.似乎for循环需要包装在某些东西中,然后返回一个值,指示sendForm可以提前 go 并发送表单。 I just can't get my head around how that is done.我只是无法理解这是如何完成的。

If you change your method like this, that should work as expected:如果您像这样更改您的方法,那应该可以按预期工作:

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