公共请求的promsie的封装
export function getJseKey ({value = '' } = {}) {
return new Promise((resolve, reject) => {
getEncryptKey().then(res => {
let pubKey = res.data && res.data.pub_key
const jse = new JSEncrypt()
jse.setPublicKey(`-----BEGIN PUBLIC KEY-----` +
pubKey +
`-----END PUBLIC KEY-----`)
let key = jse.encrypt(value)
resolve(key)
}).catch(err => {
reject(err)
})
})
}
原先代码
---- 公共请求的promise的封装 前
getEncryptKey().then(res => {
return res.data.pub_key
}).then(pubKey => {
// 通过公钥加密密码
let { key } = this.setKey({ pubKey, value: this.data.password })
----
// 请求登录接口
let params = {
account: this.data.phoneNum,
password: key
}
return signInByPassowrd(params)
}).then(res => {
token = res.token
isNewUser = res.data.is_new_user
userModel = res.data
wx.setStorageSync('token', token)
// isNewUser = true
return utils.getWxcode()
}).then(res => {
// 获取openid
return fetchOpenId({ js_code: res.code })
}).then(res => {
userModel.openid = res.data.openid
if (isNewUser) {
// 临时存储
app.globalData.token = token
app.globalData.userModel = userModel
callback(token, isNewUser)
} else {
wx.setStorageSync('userModel', userModel)
callback(token, isNewUser)
}
}).catch(err => {
console.log("登录接口-报错", err)
wx.hideLoading()
wx.showToast({
title: err && err.msg ? err.msg : '登录接口出错',
icon: 'none',
duration: 2000
})
})
现在的代码
----- 公共请求的promise的封装 后
getJseKey({ value: this.data.password }).then(passwordKey => {
// 请求登录接口
let params = {
account: this.data.phoneNum,
password: passwordKey
}
-----
return signInByPassowrd(params)
}).then(res => {
token = res.token
isNewUser = res.data.is_new_user
userModel = res.data
wx.setStorageSync('token', token)
// isNewUser = true
return utils.getWxcode()
}).then(res => {
// 获取openid
return fetchOpenId({ js_code: res.code })
}).then(res => {
userModel.openid = res.data.openid
if (isNewUser) {
// 临时存储
app.globalData.token = token
app.globalData.userModel = userModel
callback(token, isNewUser)
} else {
wx.setStorageSync('userModel', userModel)
callback(token, isNewUser)
}
}).catch(err => {
console.log("登录接口-报错", err)
wx.hideLoading()
wx.showToast({
title: err && err.msg ? err.msg : '登录接口出错',
icon: 'none',
duration: 2000
})
})
网友评论