简体   繁体   English

如何使用 axios vuejs 处理异步函数

[英]how can I handle async functions with axios vuejs

To refactor code I split it in three files为了重构代码,我将它分成三个文件

Users.vue when I have a method getUsers当我有方法 getUsers 时,Users.vue

getUsers() {
      this.isLoading = true
      this.$store
        .dispatch('auth/getValidToken')
        .then((data) => {
          this.$store
            .dispatch('user/fetchUsers', data.jwt)
            .then((response) => {
              console.log('DATA RESPONSE 2', response)
              this.items = response
              this.isLoading = false
            })
            .catch((error) => {
              console.log(error)
            })
        })
        .catch((error) => {
          this.$router.push('/pages/login')
          console.log(error)
        })
    },

user.js when I have an action user.js 当我有动作时

fetchUsers(context, jwt) {
    return UserService.getUsers(jwt)
  },

And UserServices.js when I have a function to call the api和 UserServices.js 当我有一个 function 来调用 api

async getUsers(jwt) {
    apiUsers.defaults.headers.common['jwt'] = jwt
    await apiUsers.get('/users').then((response) => {
      console.log('DATA RESPONSE 1', response.data)
      let data = response
      return data
    })
  },

As you can see I put console log messages to track the api response如您所见,我将控制台日志消息用于跟踪 api 响应

DATA RESPONSE 1 show me as I expected an object with users data but... DATA RESPONSE 2 show me a message 'undefined' DATA RESPONSE 1 向我展示了我所期望的带有用户数据的 object 但是...... DATA RESPONSE 2 向我展示了一条消息“未定义”

I am beginner in vuejs, so I will appreciate any help我是 vuejs 的初学者,所以我将不胜感激

You need to return the Promise from getUsers() .您需要从getUsers()返回 Promise 。

Something like:就像是:

async getUsers(jwt) {
    apiUsers.defaults.headers.common['jwt'] = jwt
    return await apiUsers.get('/users').then((response) => {
      console.log('DATA RESPONSE 1', response.data)
      let data = response
      return data
    })
},

Please Note: You are not using async await nicely, for example, there is no need of awaiing the response in the above getUsers() you can simply return, whereas you can use async/await under your getUsers() of Users.vue.请注意:您没有很好地使用async await ,例如,不需要等待上述getUsers()中的响应,您可以简单地返回,而您可以在 Users.vue 的getUsers()下使用 async/await。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM