在開發小程序中,獲取用戶授權是一個繁瑣的步驟,覺得不錯,請點贊哦
wx.getSetting({ success (res) { console.log(res.authSetting) // res.authSetting = { // "scope.userInfo": true, // "scope.userLocation": true // } } }) 復制代碼
// 可以通過 wx.getSetting 先查詢一下用戶是否授權了 "scope.record" 這個 scope wx.getSetting({ success(res) { if (!res.authSetting['scope.record']) { wx.authorize({ scope: 'scope.record', success () { // 用戶已經同意小程序使用錄音功能,后續調用 wx.startRecord 接口不會彈窗詢問 wx.startRecord() } }) } } }) 復制代碼
微信小程序的API都是回調函數,一不小心就是回調地獄。我們可以用Promise封裝下
const promisify = fn=>(arg={})=>new Promise((resolve,reject)=>{ arg.success=function(res){ resolve(res) } arg.fail=function(err){ reject(err) } fn(arg) }) 復制代碼
使用:
const wxGetSetting = promisify(wx.getSetting) wxGetSetting().then(res=>console.log(res)) 復制代碼
// promisify接受一個fn函數 const promisify = function(fn){ // promisify返回一個函數,這個函數可以接受一個arg參數 // arg默認是空對象,因為微信小程序api都是接受一個對象參數的 return function(arg={}){ // 該參數執行后,返回一個promise對象 return new Promise((resolve,reject)=>{ // 給參數加上success和fail arg.success=function(res){ resolve(res) } arg.fail=function(fail){ reject(fail) } // 執行fn fn(arg)// fn是傳進來的wx.getSetting }) } } 復制代碼
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") }) } }) }) } 復制代碼
使用:
myAuthorize("scope.userLocation") .then(res=>console.log(res)) .catch(err=>console.log(err)) 復制代碼