小程序Page里的函数比app.js先执行的解决办法

小程序Page里的函数比app.js先执行的解决办法

问题描述:

当我们初始化一个小程序时,默认文件 app.js 中有onLaunch函数,

onLaunch: function () {
    console.log("onLaunch");
    wx.login({
      success: res => {
        console.log("login");
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
}

默认目录,"pages/index/index", 中index.js 有 onLoad函数

onLoad: function () {
    console.log("index onLoad");
}

小程序网络请求默认为异步请求,在app.js的onLaunch运行后进行异步请求时,程序不会停止,index.js页已执行onload, onload里面的数据会因为没有获取到app.js里的东西而报错, 我们希望onLaunch执行完后再执行onLoad。

他们的执行顺序是:
onLaunch > index onLoad > login

我们希望的执行顺序是:
onLaunch > login > index onLoad

解决办法

  1. 定义回调函数, onload里获取不到东西就一直获取,不执行下一步操作,直到获取到app.js的数据才继续执行。若login返回为空,则给app.js注册一个loginSuccessCallback回调,这个回调方法的执行时机,就是app.js中的异步请求完毕

  2. 把 app.js 中的 onLaunch 中方法拿到 index.js 文件中,按照自己的逻辑写

  3. 使用promise

方法1:

App({
  onLaunch: function () {
    wx.login({
      success: res => {
        this.globalData.checkLogin = true;
        //由于这里是网络请求,可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (this.checkLoginReadyCallback){
          this.checkLoginReadyCallback(res);
        }
      }
    })
  },
  globalData: {
    checkLogin: false
  }
  
  ...
})
 

//index.js
//获取应用实例
const app = getApp()
 
Page({
  data: {
    test: false
  },
  onLoad: function () {
    let that = this;
    //判断onLaunch是否执行完毕
    if (app.globalData.checkLogin){
      that.setData({
        test:true
      })
    }else{
      app.checkLoginReadyCallback = res => {
          //登陆成功后自己希望执行的,和上面一样
        that.setData({
          test:true
        })
      };
    }
  }
})

方法2:
把 app.js 中的 onLaunch 中登陆后才执行的方法拿到 index.js 文件中,这是最简单的方法

//index.js

onLoad: function () { 
    wx.login({
      success: res => {
        resolve(res); 
      }
    })
}

方法3:

// app.js中定义一个新的方法
App({
  onLaunch: function () {
    ...
  },
  getAuthKey: function (argument) {
    var that = this;
    return new Promise(function(resolve, reject){
        wx.login({
          success: res => {
            resolve(res); 
          }
        })
    })
  }
  ...
  
})

//index.js
onLoad: function () {
    ...
        
    app.getAuthKey().then(function(res){
      console.log('res')
    })
 }
发布了270 篇原创文章 · 获赞 102 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/hahahhahahahha123456/article/details/104337494