I am facing a scenario where I have an asynchronous function that iterates through an array of files for uploading. I also have another function responsible for submitting the final form, but it needs to ensure that all uploads are complete before proceeding.
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 challenge with the current code is that the await this.selectFile
statement in sendForm()
resolves as soon as one iteration of the for
loop in selectFile()
finishes. To address this, I want to find a way for sendForm()
to wait until the entire loop completes before sending the form. Any thoughts on how I can modify the code to achieve this?
It appears that the for
loop needs some sort of wrapping mechanism to signal to sendForm()
when it's safe to proceed with form submission after all files have been uploaded. I'm struggling to figure out the best approach to implement this logic.