In the development of small programs, obtaining user authorization is a tedious step, think good, please like oh

The relevant API

wx.getSetting({
  success (res) {
    console.log(res.authSetting)
    // res.authSetting = {
    // "scope.userInfo": true,
    // "scope.userLocation": true
    // }}})Copy the code
// Wx.getSetting can be used to check whether the user authorized scope. Record scope
wx.getSetting({
  success(res) {
    if(! res.authSetting['scope.record']) {
      wx.authorize({
        scope: 'scope.record',
        success () {
          // The user has agreed that the applet will use the recording function, and subsequent calls to the wx.startRecord interface will not pop up
          wx.startRecord()
        }
      })
    }
  }
})
Copy the code

Promisify related API

Wechat apPLETS are callback functions, a careless is callback hell. We can encapsulate it with Promise

const promisify = fn= >(arg={}) = >new Promise((resolve,reject) = >{
  arg.success=function(res){
    resolve(res)
  }
  arg.fail=function(err){
    reject(err)
  }
  fn(arg)
})
Copy the code

Use:

const wxGetSetting = promisify(wx.getSetting)
wxGetSetting().then(res= >console.log(res))
Copy the code

explain

// promisify accepts a fn function
const promisify = function(fn){
// promisify returns a function that accepts an arG argument
// Arg defaults to empty objects, because wechat applets accept an object parameter
  return function(arg={}){
    // After this argument is executed, a Promise object is returned
    return new Promise((resolve,reject) = >{
      // Add success and fail to the parameters
      arg.success=function(res){
        resolve(res)
      }
      arg.fail=function(fail){
        reject(fail)
      }
      / / execution fn
      fn(arg)// fn is passed in wx.getSetting}}})Copy the code

Simplify the authorization

const wxGetSetting = promisify(wx.getSetting)
const wxAuthorize = promisify(wx.authorize)
function myAuthorize(authSetting) {
    return new Promise((resolve, reject) = > {
        wxGetSetting().then(res= > {
            if (res.authSetting[authSetting]) {
                resolve("ok")}else {
                return wxAuthorize({
                    scope: authSetting
                }).then(res= > {
                    resolve("ok")
                }).catch(err= > {
                    reject("fail")})}})})}Copy the code

Use:

myAuthorize("scope.userLocation")
  .then(res= >console.log(res))
	.catch(err= >console.log(err))
Copy the code

conclusion

Author: Hu Zhiwu

Time: 2020/03/19

If you think the article is good, please give a thumbs-up. If there are any mistakes, please correct them. Haha, thank you