Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a response from a function before doing something else in vuejs

Tags:

vuejs2

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?

like image 839
hidar Avatar asked Oct 26 '17 09:10

hidar


People also ask

What does await do in Vue?

The await keyword causes your code to wait for that Promise to resolve. And whatever data is normally passed to your callback as an argument is instead returned. There is still an asynchronous AJAX call happening, but our code reads a bit more like synchronous code. The await keyword is syntactic sugar.

What does $t mean in Vue?

Vuex is a state management pattern for vue. js. $t is the injected method from vue. js or Vue. i18n.

What is $data in Vue?

Data is the private memory of each component where you can store any variables you need. Props are how you pass this data from a parent component down to a child component. Join 11,067 other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.

What is $V in Vue?

$v is an object that calls vuelidate (at the time of writing the comment, supported in version Vue.


1 Answers

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)
    })
  }
}
like image 114
Nicolas Beauvais Avatar answered Nov 01 '22 14:11

Nicolas Beauvais