【问题标题】:How to wait for a loop to finish in an async function before executing code in another async function?如何在另一个异步函数中执行代码之前等待一个循环在异步函数中完成?
【发布时间】:2020-05-25 03:28:47
【问题描述】:

我有一个异步函数,它循环遍历需要上传的文件数组。我有另一个用于最终表单提交的功能,需要等待所有上传完成后再提交表单。

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 循环的一次迭代完成,sendForm() 中的await this.selectFile 部分就会被执行。我需要等到所有文件都上传完...那么如何让sendForm() 中的await selectFile 等待整个循环完成?

似乎for 循环需要包装在某些东西中,然后返回一个值,指示sendForm 它可以继续发送表单。我只是无法理解这是如何完成的。

【问题讨论】:

  • 您的语法存在一些问题。当您执行“等待”时,您不需要使用 .then。例如,您可以执行 'let response = await this.$axios.post('/api', FormFile);'。此外,在 sendForm 函数中,您执行“await this.selectFile”,但由于它是一个函数,因此应该是“await this.selectFile();”。检查代码时,这些错误可能会给您带来奇怪的结果。

标签: javascript vue.js


【解决方案1】:

如果你像这样改变你的方法,那应该会按预期工作:

async selectFile() {
  await Promise.all(
      this.Form.PostFiles.map(async(el, i) => {
         const File = this.Form.PostFiles[i][0];
         await this.uploadFile(File)             
    })
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-02
    • 2019-06-17
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多