在Vuex中执行async / await操作

时间:2017-12-21 01:24:38

标签: vue.js async-await vuex

我想知道如何在Vuex中使用async / await动作。 docs提供此语法作为示例:

actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // wait for `actionA` to finish
    commit('gotOtherData', await getOtherData())
  }
}

按照这个例子,我有:

import Vue from 'vue';
import Vuex from 'vuex';
import * as firebase from 'firebase';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        // other state vars here
        resource: null
    },
    mutations: {
        // saveValues
        setResource(state, payload) {
            state.resource = payload;
        }
    },
    actions: {
        async getResource({ commit, dispatch }) {
            var resource
            console.log('resource1: ' + resource)
            Vue.http.get('https://mysite/api/getResource')
                .then((response) => {
                    console.log('get resource')
                    var data = response.body;
                    resource = data.access_resource;
                    console.log('resource2: '+ resource)
                    commit('setResource', resource);
                    var foo = store.getters.resource;
                    console.log('resource3: ' + foo);
                }, (error) => {
                    console.log(error);
                });
        },
        async getSomeApi({ commit, dispatch }) {
            console.log('getting api');
            await dispatch('getResource');
            var resource = store.getters.resource;
            console.log('resource4: ' + resource);
            Vue.http.get('https://somesite/api/someapi?resource=' + resource)
                .then((response) => {
                    console.log("got something from somesite")
                    var data = response.body;
                    // do something with data -> payload
                    dispatch('saveValues', payload);
                }, (error) => {
                    console.log(error);
                });
        }
    },
    getters: {
        resource(state) {
            return state.resource;
        }
    }
});

但是,即使遵循文档中的语法示例,当我运行此代码时,async / await似乎完全被忽略。当我查看日志时,我看到,按以下顺序:

  • getting api
  • resource1: undefined
  • resource4: null
  • get resource
  • resource2: <expected-value>
  • resource3: <expected-value>

我希望console.log语句按数字顺序打印出来。如果有人能澄清我做错了什么,我将不胜感激。

1 个答案:

答案 0 :(得分:15)

await方法中的Vue.http.get()承诺不是getResource(),因此await dispatch('getResource')将在HTTP请求解决之前解析。

修剪:

async getResource() {
    let response

    try {
        response = await Vue.http.get('https://mysite/api/getResource')
    } catch (ex) {
        // Handle error
        return
    }

    // Handle success
    const data = response.body
}