Async/Await with Vuex dispatch

后端 未结 2 1739
温柔的废话
温柔的废话 2021-02-05 12:44

I am making a loader for some components in my app.

Here is my component:

        mounted() {
            this.loading = true;

            this.getProdu         


        
2条回答
  •  春和景丽
    2021-02-05 13:41

    Change this:

    getProducts({commit}, type) {
        axios.get(`/api/products/${type}`)
            .then(res => {
                let products = res.data;
                commit('SET_PRODUCTS', {products, type})
            }).catch(err => {
            console.log(err);
        })
    },
    

    To this:

    getProducts({commit}, type) {
        return axios.get(`/api/products/${type}`)
            .then(res => {
                let products = res.data;
                commit('SET_PRODUCTS', {products, type})
            }).catch(err => {
            console.log(err);
        })
    },
    

    Should work.

    axios.get returns a promise. You would need to return that promise in order to let await wait for it. Otherwise, you are implicitly returning undefined and await undefined would immediately resolve.

提交回复
热议问题