简体   繁体   中英

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. I have another function for a final form submit that needs to wait for ALL the uploads to have finished before submitting the form.

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. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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