Add immediate startup login and loading states for mini program home
This commit is contained in:
+24
-13
@@ -2,22 +2,33 @@ App({
|
||||
globalData: { token: "", user: null },
|
||||
onLaunch() {
|
||||
this.globalData.token = wx.getStorageSync("pet_token") || "";
|
||||
// Start immediately; pages await the same promise and display failures themselves.
|
||||
this.login().catch(() => {});
|
||||
},
|
||||
async login() {
|
||||
if (this.loginPromise) return this.loginPromise;
|
||||
if (this.globalData.token) return this.globalData.token;
|
||||
if (!this.loginPromise)
|
||||
this.loginPromise = (async () => {
|
||||
const { request } = require("./utils/api");
|
||||
const { code } = await wx.login();
|
||||
if (!code) throw new Error("微信登录未取得凭证,请重试");
|
||||
const data = await request("/auth/login", "POST", { code }, false);
|
||||
this.globalData.token = data.token;
|
||||
this.globalData.user = data.user;
|
||||
wx.setStorageSync("pet_token", data.token);
|
||||
return data.token;
|
||||
})().finally(() => {
|
||||
this.loginPromise = null;
|
||||
});
|
||||
this.loginPromise = (async () => {
|
||||
const { request } = require("./utils/api");
|
||||
const { code } = await new Promise((resolve, reject) =>
|
||||
wx.login({
|
||||
timeout: 10000,
|
||||
success: resolve,
|
||||
fail: () => reject(new Error("暂时无法连接微信,请重新连接")),
|
||||
}),
|
||||
);
|
||||
if (!code) throw new Error("微信登录未取得凭证,请重新连接");
|
||||
const data = await request("/auth/login", "POST", { code }, false);
|
||||
if (!data || typeof data.token !== "string" || !data.token) {
|
||||
throw new Error("登录未完成,请重新连接");
|
||||
}
|
||||
this.globalData.token = data.token;
|
||||
this.globalData.user = data.user;
|
||||
wx.setStorageSync("pet_token", data.token);
|
||||
return data.token;
|
||||
})().finally(() => {
|
||||
this.loginPromise = null;
|
||||
});
|
||||
return this.loginPromise;
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user