Home >Web Front-end >JS Tutorial >WeChat Mini Program API Encapsulation
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 } }) } } })It can be seen that when there are two layers, the code is very awkward
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) }) }The additional parameters passed are passed through object destructuring
promisify('getUserInfo') .then((res) => console.log(res)) .catch((err) => {console.error(err)}) promisify('navigateTo', { url })I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website! Recommended reading:
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!