Async/Await with Vuex dispatch

后端 未结 2 1767
温柔的废话
温柔的废话 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:27

    You can not await a function without promise

    await this.$store.dispatch('product/getProducts', 'bestseller');
    

    This function return data or call new action

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

    And this function return promise because of async function

    async function return promise
    
    async getProducts({commit}, type) {
        let res = await axios.get(`/api/products/${type}`);
    
        commit('SET_PRODUCTS', {products: res.data, type});
    
    }
    

    Now using above function now you can use

    await this.$store.dispatch('product/getProducts', 'bestseller');
    

    with await key word Or you can return axios because axios also return a promise.

提交回复
热议问题