项目场景:
首次vue加载页面,请求两个接口,后者接口需要依赖前者接口的数据去请求。
解决方法一 async/await
第一种写法
async getList(){
const res = await this.AxiosGetById()
const id =res.data.id
const resData = await this.AxiosGetList(id)
}
第二种写法
async getById(){
const res = await this.AxiosGetById()
this.id=res.data.id
},
async getList(){
await this.getById()
const resData = await this.AxiosGetList(this.id)
}
解决方法二 Promise.then()来让两个异步请求有先后顺序执行
实现代码如下
getById() {
return new Promise((resolve, reject) => {
// 发送第一个请求,获取 id
this.$http.get('getid').then(({ data }) => {
this.id = data.id;
resolve();
}).catch(err => {
console.log(err.msg);
reject(err.msg);
});
})
}
getList() {
this.getById().then(() => {
console.log(this.id) //此时的id就会正常出来;
// 使用 id 发送第二个请求
this.$http.get(`getlist?id=${this.id}`).then(({ data }) => {
console.log(data);
}).catch(err2 => {
console.log(err2.msg);
reject(err2.msg);
});
});
}