refactor: 重构登录逻辑使用 async/await
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
// app.js
|
||||
const { BASE_URL, API } = require('./utils/config')
|
||||
const { request } = require('./utils/api')
|
||||
|
||||
App({
|
||||
onLaunch() {
|
||||
@@ -24,35 +25,28 @@ App({
|
||||
})
|
||||
},
|
||||
|
||||
loginWithCode(code) {
|
||||
wx.request({
|
||||
url: BASE_URL + API.LOGIN,
|
||||
method: 'GET',
|
||||
data: { code },
|
||||
success: (res) => {
|
||||
const result = res.data
|
||||
if (result && result.code === 0 && result.data) {
|
||||
const userInfo = {
|
||||
openid: result.data.openid,
|
||||
sessionKey: result.data.session_key,
|
||||
unionid: result.data.unionid || ''
|
||||
}
|
||||
this.globalData.userInfo = userInfo
|
||||
this.globalData.isLoggedIn = true
|
||||
wx.setStorageSync('userInfo', userInfo)
|
||||
if (this.loginReadyCallback) {
|
||||
this.loginReadyCallback(userInfo)
|
||||
}
|
||||
} else {
|
||||
console.error('后端登录失败', result)
|
||||
this.handleLoginFail()
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('请求后端登录接口失败', err)
|
||||
this.handleLoginFail()
|
||||
async loginWithCode(code) {
|
||||
try {
|
||||
const data = await request({
|
||||
url: BASE_URL + API.LOGIN,
|
||||
method: 'GET',
|
||||
data: { code }
|
||||
})
|
||||
const userInfo = {
|
||||
openid: data.openid,
|
||||
sessionKey: data.session_key,
|
||||
unionid: data.unionid || ''
|
||||
}
|
||||
})
|
||||
this.globalData.userInfo = userInfo
|
||||
this.globalData.isLoggedIn = true
|
||||
wx.setStorageSync('userInfo', userInfo)
|
||||
if (this.loginReadyCallback) {
|
||||
this.loginReadyCallback(userInfo)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('后端登录失败', err)
|
||||
this.handleLoginFail()
|
||||
}
|
||||
},
|
||||
|
||||
handleLoginFail() {
|
||||
|
||||
Reference in New Issue
Block a user