hidar
hidar

Reputation: 5939

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?

Upvotes: 5

Views: 6062

Answers (1)

linasmnew
linasmnew

Reputation: 3977

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

Upvotes: 6

Related Questions