Promise 实现小程序同步请求

util.js

var Promise = require('bluebird.js')  //我用了bluebird.js 文件地址  https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js
function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }

      obj.fail = function (res) {
        reject(res)
      }

      fn(obj)
    })
  }
}

module.exports = {
  wxPromisify: wxPromisify
}


index.js 

var util = require('../../utils/util.js');

onLoad: function (options) {
  var that = this;
  uid = wx.getStorageSync('user_id');

  if (uid == '') {
   # 注意:wxPromisify括号中的方法不需要加括号直接wx.login, wxPromisify括号中的方法,我试了试自己定义的方法好像不可以,所以现在我用的是微信自带的方法。我的业务中暂时也只有授权用到同步..................
    var wxLogin = util.wxPromisify(wx.login);    

    var wxgetUserInfo = util.wxPromisify(wx.getUserInfo);

    wxLogin().then(function (res) {
      var data = {
        code: res.code
      };
      api._post(api.HOST_URI + 'appletsys/getUserOpenId', data, function (res) {
        wx.setStorageSync('openid', res.data.data.openid);
        wx.setStorageSync('token', res.data.data.token);
      })
    }).catch(function (res) {
      wx.showToast({
        title: '登录失败!',
        icon: 'loading',
        duration: 1000
      })
    })

    wxgetUserInfo().then(function (res) {
      console.log(res);
      wx.setStorageSync('icon', res.userInfo.avatarUrl);
      wx.setStorageSync('nickName', res.userInfo.nickName);
      var data = {
        user_nick: res.userInfo.nickName,
        icon: res.userInfo.avatarUrl,
        openid: wx.getStorageSync('openid'),
        token: wx.getStorageSync('token')
      }
      api._post(api.HOST_URI + 'user/registerUser', data, function (res) {
        console.log(res);
        wx.setStorageSync('user_id', res.data.data.id);

        if (res.data.data.id) {
             console.log('注册成功');
        }
      });
    }).catch(function (res) {
      wx.showToast({
        title: '请重新授权!',
        icon: 'loading',
        duration: 1000
      })
    })

  }

},

你可能感兴趣的:(WxApplet)