微信小程序中wx.login和wx.getUserProfile的使用


在使用微信登錄時,通常會在調用wx.login獲取code后再通過wx.getUserProfile獲取iv和encryptedData(加密數據)一起發到后端進行登錄驗證

在實際使用中如果在wx.login方法調用后再調用再使用wx.getUserProfile會報錯

官方解釋:

 也就是說不能在調用方法的回調中使用wx.getUserProfule()

解決方法:使用Promise.all()方法實現平級調用

Promise.all() 方法接收一個promise的iterable類型(注:Array,Map,Set都屬於ES6的iterable類型)的輸入,並且只返回一個Promise實例, 那個輸入的所有promise的resolve回調的結果是一個數組。這個Promise的resolve回調執行是在所有輸入的promise的resolve回調都結束,或者輸入的iterable里沒有promise了的時候。它的reject回調執行是,只要任何一個輸入的promise的reject回調執行或者輸入不合法的promise就會立即拋出錯誤,並且reject的是第一個拋出的錯誤信息。

簡單點說就是會等到兩個方法都回調成功該方法才會返回來值,返回值是一個數組。

上代碼

封裝wx.login和wx.getUserProfile兩個接口

 1  /**
 2    * 使用promise封裝用戶信息接口
 3    */
 4   getUserInfo:function(){
 5     return new Promise((resolve,reject) => {
 6       wx.getUserProfile({
 7         desc: '用戶登錄', // 聲明獲取用戶個人信息后的用途,后續會展示在彈窗中,請謹慎填寫
 8         success: (res) => {
 9           resolve(res)
10         },
11         fail:(err) => {
12           reject(err)
13         }
14       })
15     })
16   },
17 
18   /**
19    * 使用promise封裝wx.login接口
20    */
21   getLogin:function(){
22     return new Promise((resolve,reject) => {
23       wx.login({
24         success (res) {
25           resolve(res)
26         },
27         fail: (err) => {
28           reject(err)
29         }
30       })
31     })
32   },
View Code

封裝登錄接口

 1   /**
 2    * 登錄接口
 3    */
 4   login: function(){
 5     let userRes = this.getUserInfo()
 6     let loginRes = this.getLogin()
 7     //使用promise.all()平級調用
 8     Promise.all([userRes,loginRes])
 9     .then((res) => {
10       console.log(res)
11       let param = {
12         code: res[1].code,
13         iv: res[0].iv,
14         encryptedData: res[0].encryptedData
15       }
16       let data = {
17         method: "post",
18         url: api.apiName.wxLogin,
19         params: param
20       }
21       request.request(data)
22       .then(res => {
23         wx.setStorageSync('token', res.data)
24         wx.setStorageSync('hasLogin', true)
25         //獲取用戶信息
26         let data = {
27           method: "get",
28           url: api.apiName.getUserInfo,
29           params: null
30         }
31         request.request(data)
32         .then(res2 => {
33           wx.hideLoading({})
34           wx.setStorageSync('userInfo', res2.data)
35         })
36         .catch(err => {
37           wx.hideLoading({})
38           console.log(err.msg)
39         })
40         setTimeout(function(){
41           wx.switchTab({
42             url: '../../index/index',
43           })
44         },1500)
45       })
46       .catch(err => {
47         console.log(err.msg)
48       })
49     })
50   }
View Code

over over


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM