使用Vuex调度进行异步/等待 [英] Async/Await with Vuex dispatch

查看:606
本文介绍了使用Vuex调度进行异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的应用程序中的某些组件加载程序.

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

这是我的组成部分:

        mounted() {
            this.loading = true;

            this.getProduct();
        },
        methods: {
            async getProduct() {
                await this.$store.dispatch('product/getProducts', 'bestseller');

                console.log(123);

                this.loading = false;
            }
        },

Vuex动作:

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

问题出在这行:await this.$store.dispatch('product/getProducts', 'bestseller');

我希望代码会在该行停止,并等待从AJAX调用加载数据,然后将加载设置为false;

I expect the code will stop at that line and wait for data is loaded from AJAX call and then set the loading is false;

但不是.在我的数据准备就绪之前,仍将加载设置为false并运行console.log.

But it isn't. The loading is still set false and the console.log run before my data is ready.

我已经尝试将async/await移到Vuex动作中,并且它起作用了.但是,我没有得到它们之间的区别.

I already tried to move async/await into Vuex action and it worked. However, I didn't get the difference between them.

以下代码对我有用:

组件:

mounted() {
            this.loading = true;

            this.$store.dispatch('product/getProducts', 'bestseller').then((res) => {
                this.loading = false;
            });
        },

Vuex动作:

async getProducts({commit}, type) {
        let res = await axios.get(`/api/products/${type}`);

        commit('SET_PRODUCTS', {products: res.data, type});
    }

推荐答案

更改此内容:

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

对此:

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);
    })
},

应该工作.

axios.get返回一个承诺.您需要返回该承诺,以便让await等待它.否则,您将隐式返回undefined,而await undefined将立即解决.

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.

这篇关于使用Vuex调度进行异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆