javascript - How to await axios response before emitting response in vuejs - Stack Overflow

I have a small ponent in vuejs for file uploading (using axios). I am trying to emit the response from

I have a small ponent 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?

I have a small ponent 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?

Share Improve this question edited Oct 25, 2019 at 3:44 Cœur 38.8k25 gold badges205 silver badges277 bronze badges asked Oct 28, 2017 at 13:28 hidarhidar 5,94916 gold badges49 silver badges75 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 6

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 pletes.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744236636a4564501.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信