小程序 onLaunch在onLoad后执行问题

项目中遇到这样一个问题就是需要登录之后存一个id然后发现第一次进来的时候登录方法在index的方法后执行 拿不到想要的值

解决办法

1.就是可以加一个启动页 做个缓冲

2.用promise

直接看代码实例吧

这是我的app.js

//app.js
App({
  onLaunch: function(options) {
    // 小程序启动逻辑
    // 1. 登录
    // 2. 查看用户是否授权
    // 3. 获取用户的设备信息
    var thisPage = this;
    console.log(options);
    if (options.path !== "pages/index/index") {
      console.log(1111);
      this.globalData.destPath = options.path;
    }
    wx.showLoading({
      title: "登录中",
      mask: true
    });
  },
  // login
  getLogin() {
    var that = this;
    return new Promise(function(resolve, reject) {
      // 登录
      wx.login({
        success: res => {
          console.log(res);
          //todo 发送 res.code 到后台换取 openId, sessionKey, unionId
          wx.request({
            url: that.globalData.serverHost + "/sa/login",
            data: res.code,
            method: "post",
            success: function(res) {
              console.log(res);
              wx.hideLoading();
              if (res.data.code === 0) {
                resolve(res);
              } else {
                wx.showToast({
                  title: "登录失败,请重新启动小程序",
                  mask: true
                });
                reject('error');
              }
            },
            fail: function(data) {
              wx.hideLoading();
              console.log(data);
            }
          });
        }
      });

    });
  },
  globalData: {
    userInfo: null,
    authorized: false,
    systemInfo: null,
    systemInfoStr: null,
    sessionToken: "",
  }
});

重点再这

千万别漏掉成功里的resolve(res);不然没办法执行then方法

这是index。js

  onLoad: function() {
    var that =this;
    app.getLogin().then(function (res) {
      console.log(res)
      that.attached();//初始化页面数据
    })
  },

猜你喜欢

转载自blog.csdn.net/qq_37588752/article/details/82427717