Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to await axios response before emitting response in vuejs

I have a small component in vuejs for file uploading (using axios). I am trying to emit the response from the file upload like this:

methods: {
  ...
  upload (){
    axios.put(URL).then(response => {

    console.log('response', response)
    this.$emit('uploaded', response)

    }).catch(error => {

    })
  }

}

But in this code, even though the console.log() response shows up fine, the emit shows undefined. I think the emit is getting called before the response is ready.

Is there anyway to use async/await to solve this issue?

like image 409
hidar Avatar asked Oct 28 '17 13:10

hidar


1 Answers

console.log response shows up fine but the emit shows undefined.

Not sure what you mean by that, because if the response is available inside of console.log it should also be available inside of this.$emit. (Unless this.$emit itself is giving you undefined in which case you have scoping issues, but that shouldn't be the case as you seem to be using arrow functions).

I think the emit is getting called before the response is ready

It is inside of a callback so it should only get called once the request completes.

But if you want to try async / await then do this:

async upload() {
  try {
     let response = await axios.put(URL);
     console.log('response', response)
     this.$emit('uploaded', response)
  } catch(error) {
     // error
  }
}
like image 111
linasmnew Avatar answered Nov 17 '22 01:11

linasmnew