javascript - 异步/等待 Vuex 调度

标签 javascript vue.js async-await vuex

我正在为我的应用程序中的某些组件制作一个加载器。

这是我的组件:

        mounted() {
            this.loading = true;

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

                console.log(123);

                this.loading = false;
            }
        },

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

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

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

但事实并非如此。加载仍然设置为 false 并且 console.log 在我的数据准备好之前运行。

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

下面的代码适合我:

组件:

mounted() {
            this.loading = true;

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

Vuex Action :

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 返回一个 promise 。您需要返回该 promise ,以便让 await 等待它。否则,您将隐式返回 undefined 并且 await undefined 将立即解析。

关于javascript - 异步/等待 Vuex 调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55700815/

相关文章:

c# - 异步方法是否有可能在 C# 中返回 null?

Javascript async/await 函数 - 添加多个返回

javascript - 使用 Javascript 从 HTML 表单中获取值,然后将其显示在 html 上

JavaScript + jQuery + Angular : Element is not found

javascript - 替换链接Javascript中的部分字符串

laravel - 无法解析组件 : router-link and router-view

typescript - 动态组件在 vue 的 typescript 中不起作用

javascript - 如何忽略lodash orderBy中的新行

go - 生产中的 vue-router(使用 Go 服务)

C# Fire and Forget 任务并丢弃