天天看點

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

作者:羅亞方舟吳月

微信免密支付 需要實作異步阻塞模式,通過定時雙函數實作詳細如下:

myAsyncFunc: function () {
    return new Promise(function (resolve, reject) {
      setTimeout(function () {
        console.log("myAsyncFunction done!");
        resolve({ data: "Hello,World" });
      }, 2000);
    });
  },
 
  myAsyncFunc2: function () {
    return new Promise(function (resolve, reject) {
      setTimeout(function () {
        console.log("myAsyncFunction2 done!");
        resolve({ data: "I am coming" });
      }, 2000);
    });
  },
 
  doit: async function () {
 
    var res = await this.myAsyncFunc();
    console.log(" res: " + res.data);
 
    var res2 = await this.myAsyncFunc2();
    console.log(" res2: " + res2.data);
 
    return res2.data + res.data ;
  },           

調用的時候

onLoad: function(options) {
 
    this.doit().then(res => {
      console.log(' onLoad: ' + res);
    })
}           

列印結果:

微信小程式 異步阻塞(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);
                      resolve({ data: openId });
                  }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;
              resolve({ data: 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(res.data);
                if (res.data.code == 0 || res.data.code == 1) {
                    wx.setStorageSync(util.key.bindStatus, res.data.msg.bindStatus ? res.data.msg.bindStatus : '0');
                  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 = wx.getStorageSync(util.key.openId);//使用者id
    if (openId == '') {
      await app.getOpenId();
    }
 
    //擷取擷取城市代碼
    var cityCode = wx.getStorageSync(util.key.cityCode);
    if (!cityCode) {
      await util.getLocation();
    }
    
    //擷取綁定狀态
    var bindStatus = await app.getBaseUserInfo();
 
    //獲驗證書
    var ctf = wx.getStorageSync(util.key.ctf);
    if (util.isNull(ctf)){
      await this.loadCtf();
    }
 
    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();
    }
  },