微信小程序:用 Promise 解决方案代替回调地狱。 修复 this._invokeMethod is not a function 的问题

/**
 * 将回调地狱转换为 Promise 形式
 * https://blog.csdn.net/SEAYEHIN/article/details/88663740
 * raw:
    wx.downloadFile({
        url: this.data.curImg,
        success: res => {
            console.log(20191121213856, res)
        }
    })

  now:
    async go() {
        const downloadFile = this.app.pm(wx.downloadFile)
        const res = await downloadFile({ url: this.data.curImg })
        console.log(20191121212742, res)
    }

  fixbug:  『this._invokeMethod is not a function』 —— 用.bind(ctx) 的方式解决

  如果是wx内置函数,直接使用即可,但部分API是实例API,譬如
  
  this.ctx = wx.createCameraContext()
  this.ctx.takePhoto

  如果你使用这样的方式开发的话,必定会出现上述的问题。
  const takePhoto = this.app.pm(this.ctx.takePhoto)
  await takePhoto() // this._invokeMethod is not a function

  原因其实也简单,执行的时候上下文不是实例本身,所以我们还给它即可。
  const takePhoto = this.app.pm(this.ctx.takePhoto.bind(this.ctx))
  await takePhoto()
 */
const pm = api => (options, ...params) => new Promise((resolve, reject) => api({ ...options, success: resolve, fail: reject }, ...params))

 

posted @ 2019-11-21 23:04  贝尔塔猫  阅读(1161)  评论(0编辑  收藏  举报