我们的小程序是使用uniapp vue3开发的,简化架构描述,聚焦问题
-------------------------------------------------------------------------------------
在App.vue onLaunch生命周期中会执行 我封装的多端统一登录函数,但是因为onLaunch中的获取TOKEN逻辑是异步执行的,这样的话,与页面的onLoad事件执行业务逻辑
会有一些问题,即,异步获取TOKEN与页面onLoad执行顺序并发的问题,导致有时候onLoad中调用接口获取不到TOKEN而报错,
目前看网上没有什么好的办法,于是从TOKEN获取这个切入点,思考了一下解决方案,解决方案如下:
1. 📦封装统一的类forever模式高阶函数
2. 🥣在页面onLoad中食用这个函数
代码演示如下:
/** * @description 确保TOKEN存在时,执行一个函数,超过2S失效 */ type OnAuth = (cb: () => void) => void; export const onAuthed: OnAuth = (cb) => { if (uni.getStorageSync("TOKEN")) { return cb(); } let times = 0; const loop = () => { if (times > 2000) throw Error("获取TOKEN超时"); times += 100; const isAuth = uni.getStorageSync("TOKEN"); isAuth ? cb() : setTimeout(loop, 100); }; loop(); };
// 具体页面.vue <script setup lang="ts"> // ...一堆import onLoad((options) => { onAuthed(() => { // #ifdef MP-WEIXIN const Q = decodeURIComponent(get(options, "q", "")); const option = parseQueryParams(Q); parseNavigatePage(option as Option); // #endif // #ifdef MP-ALIPAY const optionsAlipay = my.getLaunchOptionsSync(); const objAlipay = parseQueryParams( get(optionsAlipay, "query.qrCode", "") as unknown as string, ); parseNavigatePage(objAlipay as Option); // #endif }); }); </script> <template> <view pt-200rpx> </view> </template>
这里有个最大时间限制,如果超过了这个时间,那么则抛出错误,不能一直长期挂起,该抛出错误就要抛出❌
浙公网安备 33010602011771号