回调函数嵌套调用,外部回调函数异步执行的结果是嵌套的回调的执行的条件。
getData() {
axios.get("./mock/data_a.json").then((res1) => {
console.log(res1.data.code);
axios.get("./mock/data_b.json").then((res2) => {
console.log(res2.data.code);
axios.get("./mock/data_c.json").then((res3) => {
console.log(res3.data.code);
});
});
});
},
(1) 嵌套过多会影响代码的可读性和逻辑
(2) 当某个请求失败时难以定位问题,这情况被称为回调地狱
promise链式调用
methods:{
getData1(url) {
return new Promise((resolve, reject) => {
axios.get(url).then((res1) => {
if (res1.data.code <= 1) {
resolve("成功");
} else {
reject("失败");
}
});
});
},
}
mounted(){
this.getData1("./mock/data_a.json")
.then((res) => {
console.log(res);
return this.getData1("./mock/data_b.json");
})
.then((res) => {
console.log(res);
return this.getData1("./mock/data_c.json");
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
}