小程式 同步請求授權的詳解,小程式詳解
小程式 同步請求授權的詳解
需求分析:
1.在小程式首次開啟的時候,我需要同時請求擷取多個許可權,由使用者逐一授權。
([‘scope.userInfo',‘scope.userLocation',‘scope.address',‘scope.record',‘scope.writePhotosAlbum'])
問題分析:
1. wx.authorize介面同時調用,請求多個許可權,由於非同步原因,將授權請求一併發出,顯然不符合要求。
2. promise能很好的解決問題,試著嘗試了一下,下面代碼分為兩個檔案。
// scope.jsimport es6 from '../helpers/es6-promise'// 擷取使用者授權function getScope(scopeName) { return new es6.Promise(function (resolve, reject) { // 查詢授權 wx.getSetting({ success(res) { if (!res.authSetting[scopeName]) { // 發起授權 wx.authorize({ scope: scopeName, success() { resolve(0) }, fail() { resolve(1) } }) } } }) })}module.exports = { getScope: getScope }
// index.jsimport scope from "../../service/scope"Page({onShow() { let list = ["scope.userInfo", "scope.userLocation", "scope.address", "scope.record"]; // 記錄請求結果 let num = 0; // 問題1:怎麼改成迴圈方式? 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; // 調起設定介面 if (num) { wx.openSetting({ success(res) { // 允許擷取使用者資訊 if (res.authSetting["scope.userInfo"]) userService.login() } }) } else { userService.login() } }) }) }) })})
分析求解:
1.代碼中問題1寫法過於笨,但是嘗試通過迴圈方式調用寫法,又不知道如何處理回調問題。
2.wx.authorize介面,success參數官方給出的解釋是(介面調用成功的回呼函數),其實不然,實際上是介面調用成功,並且擷取到了scope指定的許可權
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!