Home » vue » Function is retuning undefined before promise is resolved

Function is retuning undefined before promise is resolved

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a vue program that is using a service to get products from an API call.

getProducts() {
    axios.get("https://jsonplaceholder.typicode.com/posts").then(function (response) {
        return response;
    }).catch(function(error){
        console.log(error);
    })
}

In the vue page that I need to call this I make the call in the created() hook like so:

  created() {
    //this returns a promise
    productservices.getProducts().then(response =>{
      this.products = response.data;
    }).catch(error => console.log(error))
    .finally(() =>{
      consol.log("All done!");
    })
  },

I can call the function no problem however it’s running the .then() and returning Undefined. Why is this happening? How do I fix?

Answers:
getProducts() {
    return axios.get("https://jsonplaceholder.typicode.com/posts")
}

Try this instead.

###

You can also use async/await

async getProducts() {
    try {
        const response = await axios.get("https://jsonplaceholder.typicode.com/posts")
        return response
    } catch(e) {
        // Do something with the error
        console.log(e)
    }
}