小程序 解决App.js和index.js异步问题(Promise解决)

微信小程序App.js中的onLaunch 与 其他页面中的onload异步问题:

        有时候发现App.js中的onLaunch中代码没执行完时,index中的onload已经执行完了,可能会出现index需要 globalData数据 不如所愿。现在暂时用Promise方法解决

理解:

var promise = new Promise(function(resolve, reject) {
 if (/* 异步操作成功 */){
 resolve(value);
 } else {
 reject(error);
 }
});

promise.then(function(value) {
 // success
}, function(value) {
 // failure
});

示例:

//app.js
var http = require('service/http.js')
App({
  onLaunch: function() {
    //调用API从本地缓存中获取数据
    // var that = this;
  },
  getAuthKey: function () {
    var that = this;
    return new Promise(function (resolve, reject) {
        // 调用登录接口
        wx.login({
          success: function (res) {
            if (res.code) {
              that.globalData.code = res.code;
              //调用登录接口
              wx.getUserInfo({
                withCredentials: true,
                success: function (res) {
                  that.globalData.UserRes = res;
                  that.globalData.userInfo = res.userInfo;
                  that.func.postReq('/api/v1/image/oauth', {
                    code: that.globalData.code,
                    signature: that.globalData.UserRes.signature,
                    encryptedData: that.globalData.UserRes.encryptedData,
                    rawData: that.globalData.UserRes.rawData,
                    iv: that.globalData.UserRes.iv
                  }, function (res) {
                    wx.setStorage({
                      key: "auth_key",
                      data: res.data.auth_key
                    })
                    var res = {
                      status: 200,
                      data: res.data.auth_key
                    }
                    resolve(res);
                    
                  })
                }
              })
            } else {
              console.log('获取用户登录态失败!' + res.errMsg);
              var res = {
                status: 300,
                data: '错误'
              }
              reject('error');
            }  
          }
        })
    });
  },
})
//index.js
  onLoad: function () {
    app.getAuthKey().then(function (res) {
      console.log(res);
      if (res.status == 200){
        var auth_key = res.data;
        app.func.req('/api/v1/image/theme-list', {
          page: 1,
          auth_key: auth_key
        }, function (res) {
          var page = that.data.pageValue + 1;
          that.setData({
            images: res.data,
            pageValue: page
          });
        });
      }else{
        console.log(res.data);
      }
    });

暂时解决。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值