1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vuexのdispatch()はPromiseを返す

Last updated at Posted at 2021-06-10

タイトルのまんまですが、久しぶりに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() の順番になります。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?