7

I have an image upload function and this upload returns a data when finished, and I have a line below that function to do another task. the problem is vuejs/js does not wait until the first function completes the task. So, this is what my code looks like:

methods : {

    uploadImage (file) {

        this.uploadModule.upload(file); 

        if(this.uploadModule.isSuccess) {
             this.images.push(this.uploadModule.response)
        }

      // someFunction()
  }
}

So, in the above example since the upload() methods takes some time, then someFunction() part gets run before the this.images.push() part.

Is there away to just wait until the upload is finished before running another function?

1
  • 2
    This doesn't has much to do with vue, just a normal how-to-async problem. What you should do really depends on what the async this.uploadModule.upload does, and what it offers to execute code after the async operation finishes. Commented Oct 26, 2017 at 9:40

1 Answer 1

7

You can return a Promise from your upload method and execute the next portion of code as a callback in the "next" method of the Promise.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

It should look like this:

methods : {

  uploadImage (file) {

    this.uploadModule.upload(file).then(function () {
      if(this.uploadModule.isSuccess) {
        this.images.push(this.uploadModule.response)
      }

      // someFunction()
    })
  }
}

You can also handle your error using the Promise reject callback if the upload does not complete and handle the error with the catch method:

methods : {

  uploadImage (file) {

    this.uploadModule.upload(file).then(function () {
      this.images.push(this.uploadModule.response)
    }).catch(function (error) {
      console.log(error)
    })
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'm already using axios with then/catch methods inside the module ... so, I'm not sure if how this can be done further
@hidar Simply return the promise axios generates, like return axios(...).then().catch(), the function around this statement will return the promise, you can upload().then() outside the upload function, and the whole code will act as if you wrote axios(...).then().catch().then(/*code in uploadImage*/)
You're the HackerMaster !!

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.