鍍金池/ 問答/HTML/ 如何在vue讓this.$store.dispatch異步函數(shù),同步執(zhí)行;即注冊(cè)

如何在vue讓this.$store.dispatch異步函數(shù),同步執(zhí)行;即注冊(cè)再獲取用戶信息后跳轉(zhuǎn)?

1.代碼如下圖:
a.注冊(cè)頁(yè)里
圖片描述

b."getUserInfo" 函數(shù)
圖片描述

2.問題在于:有時(shí)候 this.$store.dispatch('getUserInfo')還沒有執(zhí)行完,導(dǎo)致 token 和 user_id 沒有取到;就可能執(zhí)行跳轉(zhuǎn)。
我知道是由于封裝的 promise 導(dǎo)致的,但是不知道怎么變成同步,
.then().then().catch()好像沒用,而且取得數(shù)據(jù)要判斷,執(zhí)行不了。

3.原本把注冊(cè)函數(shù)也封裝了,
代碼如下:
圖片描述

當(dāng)時(shí)的寫法:

this.$store.dispatch('UserRegister');
this.$store.dispatch('GetUserInfo');
this.$router.push('home')

但是發(fā)現(xiàn),我封裝好了,不知道讓它們同步執(zhí)行,然后就把 'UserRegister'拆開了。
所以現(xiàn)在想解決上面問題后,幫我再回答下面這個(gè)問題。
非常感謝!

回答
編輯回答
伴謊

async await

2018年5月6日 23:33
編輯回答
六扇門

修改getUserInfo

getUserInfo(){
    return api....
}

然后再修改跳轉(zhuǎn)邏輯

this.$store.dispatch('getUserInfo').then(res => {
    this.$router.push('/index');
})
2017年7月27日 02:19
編輯回答
紓惘

感覺這樣封裝確實(shí)讓組件里,頁(yè)面里的代碼更簡(jiǎn)潔;
但是調(diào)用確實(shí)麻煩,可能再用一個(gè) Promise封裝,
才疏學(xué)淺,不清楚怎么來(lái)

2017年9月10日 17:35
編輯回答
孤毒

this.$store.dispatch('getUserInfo')封裝成promise返回,通過(guò)下面這樣:

this.$store.dispatch('getUserInfo').then(res => {
    this.$router.push('/index');
}).catch( err => {
    console.log(err);
})
2017年7月18日 12:48
編輯回答
深記你

試一試
Promise.all([
this.$store.dispatch('登錄注冊(cè)'),
this.$store.dispatch('獲取用戶信息')
]).then( 執(zhí)行跳轉(zhuǎn) )

2017年10月11日 15:14