2017-12-21 88 views
5

Tôi tự hỏi làm thế nào để sử dụng hành động async/await trong Vuex. Các docs cung cấp cú pháp này là một ví dụ:hành động không đồng bộ/chờ đợi trong Vuex

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

Tiếp theo ví dụ này, tôi có:

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

Tuy nhiên, thậm chí làm theo tấm gương cú pháp tìm thấy trong các tài liệu, khi tôi chạy mã này, async/chờ đợi dường như hoàn toàn bị bỏ qua. Khi tôi nhìn vào các bản ghi, tôi thấy, theo thứ tự sau:

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

Tôi mong đợi các câu lệnh console.log sẽ in ra theo thứ tự số. Tôi sẽ đánh giá cao nếu ai đó có thể làm rõ những gì tôi đang làm sai.

Trả lời

5

Bạn không phải là await lời hứa Vue.http.get() theo phương thức getResource(), vì vậy await dispatch('getResource') sẽ giải quyết trước khi yêu cầu HTTP đã được giải quyết.

Trimmed xuống:

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 
} 
Các vấn đề liên quan