Home > Web Front-end > JS Tutorial > How to operate WeChat applet api with promise

How to operate WeChat applet api with promise

php中世界最好的语言
Release: 2018-06-08 14:26:24
Original
1653 people have browsed it

This time I will show you how to operate the WeChat Mini Program API with promise, and what are the precautions for how to operate the WeChat Mini Program API with promise. The following is a practical case, let's take a look.

The reason for promise

The API of WeChat applet uses the object parameter callback mode, which can easily cause callback hell and make the code difficult to read, judge, modify and debug. .

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
      }
     })
    }
   }
  })
Copy after login

It can be seen that when there are two layers, the code is very awkward

promise reduction 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)
 })
}
Copy after login

Use the example

The extra parameters passed are passed through object destructuring

promisify('getUserInfo')
 .then((res) => console.log(res))
 .catch((err) => {console.error(err)})
promisify('navigateTo', { url })
Copy after login

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:

How to make Vue2.0 single-select mutual exclusion in practical projects

File encoding base64 upload via AJAX

The above is the detailed content of How to operate WeChat applet api with promise. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template