タイトルのまんまですが、久しぶりにVuexを触って忘れていたのでメモがてら記事にします。
環境
- vuex: 3.6
説明
dispatch()はPromiseを返すみたいです。
なので、dispatch()は非同期です。
store
actions: {
  actionA({ commit }) {
    //このmethodTooLong()は時間がかかる
    const result = methodTooLong()
  },
},
呼び出し側
dispatch('actionA')
method2()
methodTooLong()の処理が長い場合、method2() → commit("end", result)の順番で実行されます。
処理順序を制御する?
ふむふむ そうだった。思い出した。
ということは、長い処理にawaitをつけって と、、、、、
store
actions: {
  async actionA({ commit }) {
    //awaitをつけて処理を待つ(methodTooLong()はPromiseを返す想定)
    const result = await methodTooLong()
    //methodTooLong()が終わったらcommit
    commit("end", result)
  },
},
呼び出し側
dispatch('actionA')
method2()
methodTooLong()にawaitを付けているし、これでcommit("end", result) → method2()の順番になるだろう
、、、といつも引っかかってしまいます。
結論
しかし、dispatch()は非同期 なのでした。
なので、、、
store
//↓ここは上に書いた内容と同じです。
actions: {
  async actionA({ commit }) {
    //awaitをつけて処理を待つ(methodTooLong()はPromiseを返す想定)
    const result = await methodTooLong()
    //methodTooLong()が終わったらcommit
    commit("end", result)
  },
},
呼び出し側
//ここにもawaitをつける
await dispatch('actionA')
method2()
dispatch()自体にもawaitを付けることで commit("end", result) → method2() の順番になります。
