Promise调用两个接口,第二个接口的入参为第一个接口的返回值
应用场景
Promise调用两个接口,第二个接口的入参为第一个接口的返回值
实例
1.两个接口的调用,正常的写法
// 登录接口
function login(userInfo) {
return new Promise(function(resolve, reject) {
axios.get("/jeecg-boot/login/api/getLzUserDetailByToken", { params: userInfo }).then((ress) => {
if (ress.data.code == 200) {
let userInfo = ress.data.result;
window.sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
resolve(ress)
}
})
.catch(() => {
console.log("a")
reject()
})
})
}
// 获取token
function getCpToken(userInfo) {
return new Promise(function(resolve, reject) {
axios.post("/jeecg-boot/login/api/getUserToken", userInfo)
.then((ress) => {
if (ress.data.result) {
let token = ress.data.result;
window.sessionStorage.setItem("Token", token);
window.sessionStorage.setItem("InfoCode", ress.data.code);
resolve(ress)
}
})
.catch(() => {
console.log("b")
reject()
})
})
}
2.实现异步调用
first().then( firstData =>{
return second({入参:})
})
.then(secondData =>{})
login({accessToken:userId})
.then((firstData) => {
// 使用第一个接口返回的参数调用第二个接口
return getCpToken(firstData.data.result);
})
.then((secondData) => {
if (to.path == '/' || to.path == '/start') {
next('/cpIndex')
} else {
next()
}
})
.catch(() => {
Toast.fail('登录失败');
})