业务需求
最近写小程序的时候遇到想要在前端通过调用接口的结果,来判断是跳转到注册页面还是首页
方式一:通过callback
//index.js页面
//如果登录凭证code不为空
if (res.code) {
dispatch({
type: 'VerificationModel/getToken',
payload: {
code: res.code,
appid: appId,
jobNum: '',
},
callback: (response) => {
if (response.code === 0) {
Taro.showToast({
title: '登录成功',
duration: 2000,
icon: 'success',
mask: false,
})
Taro.switchTab({
url: '/pages/index/index'
})
} else {
Taro.showToast({
title: '未注册,请先注册',
duration: 2000,
icon: 'none',
mask: false,
})
Taro.redirectTo({
url: '/pages/Register/index'
})
}
}
})
}
//model.js页面
effects: {
* getToken({payload, callback}, {call, put}) {
const response = yield call(VerificationService.getAccessToken, payload);
const {code} = response;
//调用callback
callback(response);
}
方法二:通过Promise
//index.js页面
//如果登录凭证code不为空
if (res.code) {
//new一个Promise对象,将resolve函数作为参数传给model中的异步函数
new Promise((resolve) => {
dispatch({
type: 'VerificationModel/getToken',
payload: {
code: res.code,
appid: appId,
jobNum: '',
resolve,
}
});
//then方法接收两个函数,第一个函数作为成功时的回调函数,第二个函数作为失败时的回调函数
}).then((data)=>{
console.log(data); //data打印出来是model中response的值
if (data.code === 0) {
Taro.showToast({
title: '登录成功',
duration: 2000,
icon: 'success',
mask: false,
})
Taro.switchTab({
url: '/pages/index/index'
})
} else {
Taro.showToast({
title: '未注册,请先注册',
duration: 2000,
icon: 'none',
mask: false,
})
Taro.redirectTo({
url: '/pages/Register/index'
})
}
},()=>{
console.log('failed')
})
}
//model.js页面
effects: {
* getToken({payload, callback}, {call, put}) {
const response = yield call(VerificationService.getAccessToken, payload);
const {resolve} = payload;
//调用resolve函数
resolve(response);
}