javascript 使用 Vuex 调度异步/等待

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55700815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:34:24  来源:igfitidea点击:

Async/Await with Vuex dispatch

javascriptvue.jsasync-awaitvuex

提问by user3118789

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

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

Here is my component:

这是我的组件:

        mounted() {
            this.loading = true;

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

                console.log(123);

                this.loading = false;
            }
        },

Vuex action:

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

The problem is in this line: await this.$store.dispatch('product/getProducts', 'bestseller');

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

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;

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

But it isn't. The loading is still set falseand the console.logrun before my data is ready.

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

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

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

Below code is worked for me:

下面的代码对我有用:

Component:

零件:

mounted() {
            this.loading = true;

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

Vuex action:

Vuex 动作:

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

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

采纳答案by jian

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.getreturns a promise. You would need to return that promise in order to let awaitwait for it. Otherwise, you are implicitly returning undefinedand await undefinedwould immediately resolve.

axios.get返回一个承诺。您需要返回该承诺才能await等待它。否则,您将隐式返回undefinedawait undefined立即解决。

回答by Ashok

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.

使用 await 关键字或者你可以返回 axios 因为 axios 也返回一个 promise。