zoukankan      html  css  js  c++  java
  • 微信小程序:用 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))
  • 相关阅读:
    Kafka生产者Producer配置 ,及C#中使用学习资料连接
    Oracle expdb异地备份
    查询redis当前连接数据和当前信息
    Oracle在sqldeveloper中按格式显示日期数据
    DB行转列
    2019.9.10面试反思
    配置webpack4
    代理
    es6 promise
    es6 symbol
  • 原文地址:https://www.cnblogs.com/CyLee/p/11909038.html
Copyright © 2011-2022 走看看