【微信小程序】使用 Promise、async 和 await 将异步API 改写为同步

以获取图片信息的API为例:

官方为异步的回调函数

wx.getImageInfo({
    
    
  src: 'images/a.jpg',
  success (res) {
    
    
    console.log(res.width)
    console.log(res.height)
  }
})

改写后

  // 获取图片信息
  getImgInfo(imgURL) {
    
    
    return new Promise((reslove) => {
    
    
      wx.getImageInfo({
    
    
        src: imgURL,
        success(res) {
    
    
          reslove(res);
        }
      })
    })
  },

使用方法

  async draw() {
    
    
    let ImgInfo = await that.getImgInfo(this.data.imgURL)
    console.log(ImgInfo)
  },

猜你喜欢

转载自blog.csdn.net/weixin_41192489/article/details/130078479