Home > Mobile >  vue method for loop wait for function complete
vue method for loop wait for function complete

Time:04-11

In this vue component, I have a method containing a for loop, calling another method. The second method does a request to the appserver. I need the first function waiting for the second to continue the for-loop. I've tried several async await options but doesn't understand how to implement it.

methods: {
selectFiles(files) {
  this.progressInfos = [];
  this.selectedFiles = files;
},
uploadFiles() {
  this.message = "";
  //var result = 0;
  for (let i = 0; i < this.selectedFiles.length; i  ) {
    console.log(i)
    //result = await this.upload(i, this.selectedFiles[i]);
    this.upload(i, this.selectedFiles[i]);
  }
},
upload(idx, file) {
  this.progressInfos[idx] = { percentage: 0, fileName: file.name };
  //console.log("FinDocuNum:"   financialDocument.finDocId)
  FinancialDocumentDataService.upload(1, file, (event) => {
    this.progressInfos[idx].percentage = Math.round(100 * event.loaded / event.total);
  }).then((response) => {
      let prevMessage = this.message ? this.message   "\n" : "";
      this.message = prevMessage   response.status;
      return 1;
  }).catch(() => {
      this.progressInfos[idx].percentage = 0;
      this.message = "Could not upload the file:"   file.name;
      return 0;
    });
}

}

CodePudding user response:

The upload function must be async and return a promise like this:

async upload(file) {
    return new Promise((resolve, reject) => {

        axios({url: url, data: file, method: 'POST'})
            .then(resp => {
                resolve(resp)
            })
            .catch(err => {
                reject(err)
            })
    })
},
  • Related