小程序中 Promise解決異步執(zhí)行的問題

項(xiàng)目需要獲取用戶的openid,邏輯是在app.js的onLaunch中調(diào)用wx.login方法,success之后wx.request去請(qǐng)求后臺(tái)獲取openid;
獲取成功之后在page的onLoad方法中使用;
想的很完美,但是實(shí)現(xiàn)時(shí)發(fā)現(xiàn),在wx.request還未執(zhí)行完就執(zhí)行了page的onLoad;
經(jīng)過一番掙扎,使用Promise解決了這個(gè)問題;貼上代碼以示尊重。
app.js

App({
  globalData: {
    hostUrl: "https://wxapp.becypress.com/"
  },
  onLaunch: function () {
    // 展示本地存儲(chǔ)能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  getOpenid:function(){
    var that = this;
    return new Promise(function (resolve, reject){
      wx.login({
        success: function (res) {
          if (res.code) {
            //發(fā)起網(wǎng)絡(luò)請(qǐng)求
            wx.request({
              url: that.globalData.hostUrl + 'wechat/app/login/' + res.code,
              data: {
              },
              success: function (res) {
                //resolve到index.js的then中  
                resolve(res.data.openid);
              }
            });
          } else {
            console.log('登錄失敗!' + res.errMsg)
          }
        }
      });
    }); 
  }
})

index.js

var app = getApp();
Page({
  data: {
    url:""
  },
  onLoad: function (options) {
    var that = this;
    app.getOpenid().then(function(openid){
      that.setData({
        url: app.globalData.hostUrl + "app/index.html?opneid=" + openid
      });
    });
  }
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容