Home  >  Article  >  Web Front-end  >  WeChat Mini Program API Encapsulation

WeChat Mini Program API Encapsulation

php中世界最好的语言
php中世界最好的语言Original
2018-04-28 15:10:113069browse

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 uses

objectparameter 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 API

function promisify (method, options = {}) {
 return new Promise((resolve, reject) => {
  // 将options对象赋值 然后再传给下面调用的方法中
  options.success = resolve
  options.fail = err => {
   reject(err)
  }
  wx[method](options)
 })
}

Usage example

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn