简体   繁体   中英

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() {
      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

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

And UserServices.js when I have a function to call the 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

DATA RESPONSE 1 show me as I expected an object with users data but... DATA RESPONSE 2 show me a message 'undefined'

I am beginner in vuejs, so I will appreciate any help

You need to return the Promise from getUsers() .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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