1. 程式人生 > 其它 >[轉]uni-app 中利用 Promise 實現 onLaunch 非同步回撥後執行 onLoad

[轉]uni-app 中利用 Promise 實現 onLaunch 非同步回撥後執行 onLoad

問題描述

我們在用 uni-app 開發前端專案時,會遇到需要在 onLaunch 中請求介面返回結果,並且此結果在專案各個頁面的 onLoad 中都有可能使用到的需求,比如微信小程式在 onLaunch 中進行登入後取得 openid 並獲得 token,專案各頁面需要帶上該 token 請求其他介面。但是,onLaunch 中的請求是非同步的,也就是說在執行 onLaunch 後頁面 onLoad 就開始執行了,而不會等待 onLaunch 非同步返回資料後再執行,這就導致了頁面無法拿到 onLaunch 中非同步獲取的資料。

解決方案

步驟1
在 main.js 中增加如下程式碼:

Vue.prototype.$onLaunched = new Promise(resolve => {
    Vue.prototype.$isResolve = resolve
})

步驟2
在 App.vue 的 onLaunch 中增加程式碼 this.$isResolve(),具體如下:

onLaunch () {
    // #ifndef H5
    uni.login({
        success: loginRes => {
            // #ifdef MP-WEIXIN
            login({ // 該介面為我們自己寫的獲取 openid/token 的介面,請替換成自己的
                appId: 'wx1234567890',
                code: loginRes.code
            }).then(res => {
                try {
                    console.info(res.object.token)
                    uni.setStorageSync('mcToken', res.object.token)
                    this.$isResolve()
                } catch (e) {
                    console.error(e)
                }
            })
            // #endif
        }
    })
    // #endif
}

步驟3
在頁面 onLoad 中增加程式碼 await this.$onLaunched,具體如下:

async onLoad(option) {
    await this.$onLaunched

    let token = ''
    try {
        token = uni.getStorageSync('mcToken')
    } catch(e) {
        console.error(e)
    }

    // 下面就可以使用 token 呼叫其他相關介面
}