我有一个异步功能,该功能遍历需要上传的文件数组。我还有一个用于最终提交表单的功能,该功能需要等待所有上传完成之后才能提交表单。
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.
你不能。
however you can wait in method
sendForm
forselectFile
method to finish:I would strongly suggest to change your method names because what
selectFile()
method does is - it callsuploadFile()
many times method and makes many HTTP requests which is super confusing so it's not really "selectFile" but "uploadAllFiles". It has nothingf to do with selecting files. It's super hard to read.