This time I will bring you WeChat mini program api encapsulation. What are the precautions for WeChat mini program api encapsulation? The following is a practical case, let’s take a look.
The reason for promise
The API of WeChat applet usesobjectparameter callback mode, which can easily cause callback hell and make the code difficult to read , Judgment, modification and Debugging.
WeChat applet api example
// 获取用户信息 wx.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 wx.getUserInfo({ success: res => { // 可以将 res 发送给后台解码出 unionId this.globalData.userInfo = res.userInfo } }) } } })
Promise small program
Write a public function that can promise the small program APIfunction promisify (method, options = {}) { return new Promise((resolve, reject) => { // 将options对象赋值 然后再传给下面调用的方法中 options.success = resolve options.fail = err => { reject(err) } wx[method](options) }) }
promisify('getUserInfo') .then((res) => console.log(res)) .catch((err) => {console.error(err)}) promisify('navigateTo', { url })
Detailed explanation of the steps to implement an arc-shaped dragging progress bar
angular6.0 implements lazy loading of components Function (with code)
The above is the detailed content of WeChat Mini Program API Encapsulation. For more information, please follow other related articles on the PHP Chinese website!