0

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;
    });
}

}

3
  • You don't return a promise from upload, so there's nothing to await Commented Apr 10, 2022 at 13:26
  • @EstusFlask, so I must make Upload return a promise in order for this to work? Commented Apr 10, 2022 at 13:53
  • 1
    And await for it, yes Commented Apr 10, 2022 at 14:20

1 Answer 1

1

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)
            })
    })
},
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.