javascript - 如何在另一个异步函数中执行代码之前等待一个循环在异步函数中完成?
问题描述
我有一个异步函数,它循环遍历需要上传的文件数组。我有另一个用于最终表单提交的功能,需要等待所有上传完成后再提交表单。
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)
}
}
上面代码的问题在于,只要循环 in的一次迭代完成,inawait this.selectFile
部分就完成了。我需要等到所有文件都上传...那么我该如何等待整个循环完成?sendForm()
for
selectFile()
await selectFile
sendForm()
看起来for
循环需要被包裹起来,然后返回一个值,表明sendForm
它可以继续发送表单。我只是无法理解这是如何完成的。
解决方案
如果您像这样更改您的方法,那应该可以按预期工作:
async selectFile() {
await Promise.all(
this.Form.PostFiles.map(async(el, i) => {
const File = this.Form.PostFiles[i][0];
await this.uploadFile(File)
})
);
}
推荐阅读
- python - 将元组列表(不同长度)转换为字典
- react-native - react native:在scrollView中使用stickyHeaderIndices时如何知道组件是粘性的
- vba - 需要来自 DB 中另一个表的数据来生成电子邮件而无需额外查询
- node.js - 在 Node JS 中注册相同的事件监听器两次还是两个不同的监听器?
- javascript - 从#document 中访问外部 html 内容
- php - PHP - 解析 xml 文件 - 交付的文件包含一个带有“-”的属性,当我运行 php 时会生成一个警告
- python - 匹配两个数据库中具有相似但不精确匹配的数据行的名称
- reactjs - 没有复选框的反应表选择行
- pyspark - Spark 阅读 Cassandra
- r - 基本闪亮的应用程序。为什么 source('app.R') 不起作用?