Uniapp 与 原生小程序使用差异:promise
发布于 3 年前 作者 yangtan 4817 次浏览 来自 分享

1、首先,如果用 callback 方式,也就是常见的的success的方式,uniapp和wx调用方法一致,返回值也一致,如:

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

2、重点需要说的是 promise方式,即带then()的方式,类似于:

wx.getImageInfo().then(res => console.log('res: ', res)

这里需要注意,使用原生方法,因为没有捕获错误,需要套一层 try{}catch(){}

try{
	wx.getImageInfo().then(res => console.log('res: ', res)		
}catch(e){
  //TODO handle the exception
}

uniapp则封装好了 ,

var [error, res] = uni.getImageInfo({src: path})

返回值直接就是 一个带错误的数组,
没有错误的时候:error = null
回到顶部