const auth = require('./utils/auth'); const api = require('./utils/api'); App({ onLaunch() { // 尝试登录并缓存用户信息 auth.ensureLogin() .then((token) => { if (token) { // 登录成功后预取 profile 缓存到 globalData api.request({ url: '/api/v1/profile' }) .then((res) => { this.globalData.user = res; }) .catch(() => { // 预取失败不影响主流程 }); } }) .catch(() => {}); }, globalData: { token: '', user: null }, // 全局获取用户信息(带缓存) getUserInfo(force) { if (this.globalData.user && !force) { return Promise.resolve(this.globalData.user); } return auth.ensureLogin() .then((token) => { if (!token) return null; return api.request({ url: '/api/v1/profile' }); }) .then((user) => { if (user) { this.globalData.user = user; } return user; }); }, });