封装代码 

/**
 * 将小程序的API封装成支持Promise的API
 * @params fn {Function} 小程序原始API,如wx.login
 */
public wxPromisify: Function = fn => {
  return function (obj = {}) {
      return new Promise((resolve, reject) => {
        obj.success = function (res) {
          resolve(res)
        }    
        obj.fail = function (res) {
          reject(res)
        }
        fn(obj)
      })
  }
}

使用代码

public created() {
  this.wxPromisify(wx.getSystemInfo)()
    .then(res => {
       let ratio = res.windowWidth / 750
       that.setData({
         ratio: ratio,
       })
    })
}

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐