微信小程序 使用Promise封装API

wx.getUserInfo

获取用户信息

1
2
3
4
5
6
7
8
9
wx.getUserInfo({
withCredentials: true,
success(res) {
console.log(res.userInfo)
},
fail(error){
console.log(error)
}
})

Promise

使用Promise封装微信小程序的大部分API,把这个函数写在一个公共js文件下。这里首先创建一个带有’original’参数的匿名函数赋值给promisify,匿名函数里返回一个携带微信小程序原生API需要传参数的’opt’的函数,最终返回一个promise函数实例。

1
2
3
4
5
6
7
8
9
10
11
const promisify = original => {
return function (opt) {
return new Promise((resolve, reject) => {
opt = Object.assign({
success: resolve,
fail: reject
}, opt)
original(opt)
})
}
}

接着,在pages中对应页面的js文件中引入

1
2
3
4
5
6
7
8
const utils = require('../../utils/util.js')

utils.promisify(wx.getUserInfo)({withCredentials: true})
.then(res=>{
console.log(res)
}).catch(error=>{
console.log(error)
})

参考资料

  1. 微信小程序
  2. ECMAScript 6 入门