How to dynamic call the axios method in VueJS/NuxtJs

Viewed 492

I'm trying to optimize my code. So, I dynamically use the axios function, but the returned response is a pending console log. I am using async/await. Any one can help me for this.

This is my code:

methods: {
  getAgentsNames() {
    const data = this.callAxios('get', `/getAllAgents`)
    console.log(data) // returns pending
    this.agents = data.listings
  },

  async callAxios(method, url, paramsBody = null) {
    try {
      const response = await this.$axios({
        method,
        url,
        params: paramsBody,
        headers: this.headers,
      })
      console.log(response) // success and have response data.
      if (response.data.status == 'ok') {
        return response.data
      } else {
        ifNotOK(response, this.$cookies)
        return null
      }
    } catch (error) {
      console.log(error)
      return null
    }
  },
},
1 Answers

Your top function also needs to wait for the call to return:

async getAgentsNames() {
                let data = await this.callAxios(
Related