onLaunch中的异步请求执行完之后再执行Page的onLoad

微信小程序app.js的onLaunch中的异步请求执行完之后再执行Page的onLoad

**app.js**
import {
    
     GetUserInfo } from './api/userApi';
App({
    
    
 onLaunch(){
    
    
    const that = this
    GetUserInfo().then(res =>{
    
    
			that.globalData.userInfo = res || null
			that.globalData.isRequest = true // 拿到异步请求了给true
			// 这个getUserInfoCallback在app.js中是没有定义的,在Page的onLoad方法中有给赋值
			if(that.getUserInfoCallback){
    
     
				that.getUserInfoCallback(res);
			}
		 })
    },
    globalData: {
    
    
		userInfo: {
    
    }, // 用户信息
		isRequest:false, // 默认是false,异步请求拿到结果后才给true
	},
})
**index.js**
onLoad(){
    
    
 // 这一开始拿到的是false,因为onLaunch里面的异步请求结果会在onLoad后执行
	if (app.globalData.isRequest) {
    
    
		this.setData({
    
    
			userInfo: app.globalData.userInfo,
		});
	} else {
    
    
	// 走的else,请看清楚这个地方是等号,是赋值,我没看清楚,在app.js里面纠结了好久为啥不定义能用
		app.getUserInfoCallback = res => {
    
    
			console.log(res,'回调函数拿到了-------');
			if (res != '') {
    
    
				this.setData({
    
    
					userInfo: res,
				});
			}
			console.log(app.globalData.userInfo,'回调函数拿到了-------');
		}
	}
}

划重点--------------

整个应该是我傻了,onLoad里面的那个是等号,等号,等号,重新赋值给了一个回调函数,我之前没有看清楚,百度后一直在纠结为啥app.js里面没有定义那个函数还能拿来用,当前是因为我菜,所以我看成了函数调用,各位大佬是不会犯我这个低级错误的。。。。。

猜你喜欢

转载自blog.csdn.net/weixin_45324044/article/details/122078259