1. 程式人生 > >微信小程式 非同步阻塞(Promise、resolve,await,then)

微信小程式 非同步阻塞(Promise、resolve,await,then)

1.呼叫的的函式 獲取使用者資訊(new Promise(function (resolve, reject)   resolve({ data: ‘xxxx’ });)

/**
   * 獲取openid資訊
   * add by wp 20180906
   */
  getOpenId: function() {
    return new Promise(function (resolve, reject) {
      var openId = '';
      var seKey = '';
      // 登入
      let that = this;
      wx.login({
        success: function (res) {
          // 傳送 res.code 到後臺換取 openId, sessionKey, unionId
          if (res.code) {
            //發起網路請求
            wx.request({
              url: util.url.baseUrl + 'wxpro/jscode2session',
              data: {
                appid: util.appConfig.appId,
                secret: util.appConfig.secret,
                js_code: res.code,
                grant_type: util.appConfig.grantType,
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              method: 'POST',
              success: function (result) {
                  if(result.data.code == 0){
                      seKey = result.data.msg.session_key;
                      openId = result.data.msg.openid;
                      wx.setStorageSync(util.key.openId, openId);
                      wx.setStorageSync(util.key.seKey, seKey);
                      // that.globalData.baseInfo.seKey = seKey;
                      // that.globalData.baseInfo.openId = openId;
                      resolve({ data: openId });
                      // that.getBaseUserInfo();

                  }else{
                      return wx.showToast({
                          title: '請求失敗',
                          icon: 'none',
                          duration: 2000
                      })
                  }

              },
              fail: function (res) {
                  return wx.showToast({
                      title: '請求失敗',
                      icon: 'none',
                      duration: 2000
                  });
              }
            })
          } else {
            console.log('--獲取openid失敗--');
          }

        },
        fail: function (res) {
          console.log('微信登入失敗');
        }
      })
    });
  },

2. 獲取地址位置資訊(new Promise(function (resolve, reject)   resolve({ data: ‘xxxx’ });)

function getLocation(ck) {
  return new Promise((resolve, reject)=>{
    const app = getApp();
    wx.getLocation({
      type: appConfig.locType,
      success: function(res) {
        var lat = res.latitude;
        var lng = res.longitude;
        log(TAG, 'lat=' + lat + ",lng=" + lng);
        if (lat == 'undefined' || lng == 'undefined') return;
        wx.request({
          url: url.locInfo(lat, lng),
          method: 'GET',
          success: function(res) {
            if (res) {
              var cityInfo = res.data.result.addressComponent;
              var cityCode = String(cityInfo.adcode).substring(0, 4).concat('00');
              var cityName = cityInfo.city;
              wx.setStorageSync(key.cityName, cityName);
              wx.setStorageSync(key.cityCode, cityCode);
                app.globalData.baseInfo.cityCode = cityCode;
                app.globalData.baseInfo.cityName = cityName;
              log(TAG, 'cityCode=' + cityCode);
              resolve({ data: cityCode });
              // reslove(cityCode);
              if(ck && ck.success)ck.success(cityName, cityCode);
            } else {
              // ck.fail(res);
              log("Error", "loc fail...");
            }

          },
          fail: function(res) {
            ck.fail(res);
            log("Error", res.errMsg);
          }
        })
      },
      fail:function(res){
        log(TAG,'獲取經緯度失敗~');
      },
      
    })
  });
}

3.獲取使用者資訊(new Promise(function (resolve, reject)   resolve({ data: ‘xxxx’ });)

getBaseUserInfo(){
    return new Promise(function (resolve, reject) {
        var openId = wx.getStorageSync(util.key.openId);//使用者id
        var cityCode = wx.getStorageSync(util.key.cityCode);

        if(!cityCode)return;
        if (openId == '') return;
        let that = this;
        wx.request({
            url: util.url.baseUrl + 'wxpro/getUserInfo',
            data: {
                openId: openId,
                cityCode: cityCode
            },
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            method: 'POST',
            success: function (res) {
                console.log('get baseUserInfo success____________________________');
                console.log(res.data);
                if (res.data.code == 0 || res.data.code == 1) {
                    // that.globalData.baseInfo = res.data.msg;
                    // that.globalData.baseInfo.bindStatus = res.data.msg.bindStatus ? res.data.msg.bindStatus : '0';
                    wx.setStorageSync(util.key.bindStatus, res.data.msg.bindStatus ? res.data.msg.bindStatus : '0');
                    // var bindStatus = that.globalData.baseInfo.bindStatus || wx.getStorageSync(util.key.bindStatus);
                  var bindStatus =  wx.getStorageSync(util.key.bindStatus);

                    if (bindStatus == 0) wx.navigateTo({ url: '../login/login'});
                    resolve({ data: bindStatus });
                }
                else{
                    // return wx.showToast({
                    //     title: '獲取使用者資訊失敗,錯誤碼:'+res.data.code,
                    //     icon: 'none',
                    //     duration: 2000
                    // })
                }
            }
        })
      });
    }

4.非同步阻塞函式響應處理(await)

 //非同步阻塞操作 add by wupeng 20180925
  start: async function () {
    //獲取openid
    var openid = await app.getOpenId();
    
    //獲取獲取城市程式碼
    var citycode = await util.getLocation();

    //獲取繫結狀態
    var bindStatus = await app.getBaseUserInfo();
 
    return bindStatus.data;
  },

5.在onload中執行呼叫 (this.start().then(res =>)

onLoad: function(options) {
    var bindStatus = app.globalData.baseInfo.bindStatus || wx.getStorageSync(util.key.bindStatus);
    console.log(TAG + ' onLoad: ' + bindStatus);
    if ( 0 == bindStatus){
      this.start().then(res => {
          var city = options.city || wx.getStorageSync(util.key.cityName);
          this.setData({
            loc: {
              addr: city,
            }
          });

          if (!options.flag) this.loadCtf();
          this.flushQRCode();
          this.loadNotify();
          this.loadAds();
          this.getPhoneHeight();
      })
    }else{
      var city = options.city || wx.getStorageSync(util.key.cityName);
      this.setData({
        loc: {
          addr: city,
        }
      });

      if (!options.flag) this.loadCtf();
      this.flushQRCode();
      this.loadNotify();
      this.loadAds();
      this.getPhoneHeight();
    }
  },