In Vuex action, we have the following implementation.
async actionA({ commit, dispatch }) {
const data = this.$axios.$get(`/apiUrl`)
await Promise.all([
dispatch('actionB', { data: data }),
dispatch('actionOthers'),
]).then(() => {
commit('mutationA', data)
})
}
async actionB({ commit, dispatch }, { data }) {
await this.$axios.$get('/apiUrl', { params: data }).then(res => {
if (res.length === 0) {
dispatch('actionC', { data: data })
}
commit('mutationB', res)
})
}
async actionC({ commit, dispatch }, { data }) {
await this.$axios.$get('/anotherUrl', { params: data }).then(res => {
commit('mutationC', res)
})
}
Dispatch actionB
fromactionA
and dispatch actionC
fromactionB
depending on the result of actionB
.
However, actionA
will be resolved beforeactionC
completes.
How should I cope with such cases?
If you want to avoid that actionA resolves before actionC completes, you need to await on the dispatch actionC action.
You need to rewrite your actionB like this:
async actionB({ commit, dispatch }, { data }) {
const res = await this.$axios.$get('/apiUrl', { params: data })
if (res.length === 0) {
await dispatch('actionC', { data: data })
}
commit('mutationB', res)
}