[Vuejs]-Return data from axios without it being a promise

5👍

✅

Since you have a .vue-file, I assume that this is a single-page vue component, right? And therefore you use vue-cli or webpack. I therefore assume that you can use async/await syntax.

Retrieving data from axios is asynchronous, because you basically cannot know how long it takes for it to retrieve the data over the network. And this kind of situation is what async/await is for.

So make the functions async:

products.js

export default {
    async getAllProducts(axios) {
        const response = await axios.get('fakedb.json');
        return response.data;
    }
}

product.vue:

import productController from '~/data/controllers/product';
export default {
  data() {
    return {
      products: [],
    };
  },
  async mounted: {
    this.products = await productController.getAllProducts(this.$axios);
  }
}

I do not think you can make the data function asynchronous, so return an empty data object (I have assumed that it is an array), and then use the mounted hook to retrieve data.

1👍

You can’t. A function returns immediately and there is nothing meaningful for it to return if you don’t want a promise, since loading won’t have begun yet. This is the problem that promises solve to begin with. It’s a bad pattern to make an async call into your data to begin with, though. Use this pattern instead:

data() {
  return {
    products: null
  }
},
methods: {
  getAllProducts() {
    return axios.get('fakedb.json').then(response => {
      this.products = response.data;
    });
  }
},
created() {
  this.getAllProducts();
}

The async call is abstracted out into the created hook, and when it’s resolved it will set the data accordingly.

Here’s a little demo

Leave a comment