微信小程序 同步請求授權的詳解
微信小程序 同步請求授權的詳解
需求分析:
1.在小程序首次打開的時候,我需要同時請求獲取多個權限,由用戶逐一授權。
([‘scope.userInfo',‘scope.userLocation',‘scope.address',‘scope.record',‘scope.writePhotosAlbum'])
問題分析:
1. wx.authorize接口同時調(diào)用,請求多個權限,由于異步原因,將授權請求一并發(fā)出,顯然不符合要求。
2. promise能很好的解決問題,試著嘗試了一下,下面代碼分為兩個文件。
// scope.js import es6 from '../helpers/es6-promise' // 獲取用戶授權 function getScope(scopeName) { return new es6.Promise(function (resolve, reject) { // 查詢授權 wx.getSetting({ success(res) { if (!res.authSetting[scopeName]) { // 發(fā)起授權 wx.authorize({ scope: scopeName, success() { resolve(0) }, fail() { resolve(1) } }) } } }) }) } module.exports = { getScope: getScope }
// index.js import scope from "../../service/scope" Page({ onShow() { let list = ["scope.userInfo", "scope.userLocation", "scope.address", "scope.record"]; // 記錄請求結果 let num = 0; // 問題1:怎么改成循環(huán)方式? scope.getScope(list[0]).then(function (res) { num += res; scope.getScope(list[1]).then(function (res) { num += res; scope.getScope(list[2]).then(function (res) { num += res; scope.getScope(list[3]).then(function (res) { num += res; // 調(diào)起設置界面 if (num) { wx.openSetting({ success(res) { // 允許獲取用戶信息 if (res.authSetting["scope.userInfo"]) userService.login() } }) } else { userService.login() } }) }) }) }) })
分析求解:
1.代碼中問題1寫法過于笨,但是嘗試通過循環(huán)方式調(diào)用寫法,又不知道如何處理回調(diào)問題。
2.wx.authorize接口,success參數(shù)官方給出的解釋是(接口調(diào)用成功的回調(diào)函數(shù)),其實不然,實際上是接口調(diào)用成功,并且獲取到了scope指定的權限
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
Servlet3.0與純javascript通過Ajax交互的實例詳解
Servlet與純javascript通過Ajax交互,對于很多人來說應該很簡單。不過還是寫寫,方便Ajax學習的后來者2018-03-03