[英]How to wait for a loop to finish in an async function before executing code in another async function?
我有一个异步 function 循环遍历需要上传的文件数组。 我还有另一个 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)
}
}
上面代码的问题是,只要 selectFile() 中的for
循环的一次迭代完成, selectFile()
sendForm()
中的await this.selectFile
部分就完成了。 我需要等到所有文件都上传......所以我怎样才能让sendForm()
中的await selectFile
等待整个循环完成?
似乎for
循环需要包装在某些东西中,然后返回一个值,指示sendForm
可以提前 go 并发送表单。 我只是无法理解这是如何完成的。
如果您像这样更改您的方法,那应该可以按预期工作:
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.