簡體   English   中英

在另一個異步 function 中執行代碼之前,如何在異步 function 中等待循環完成?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM