Reputation: 7563
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.
Upvotes: 0
Views: 1602
Reputation: 117
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)
})
);
}
Upvotes: 1