回调地狱:
在回调函数内, 再嵌套回调函数, 一直嵌套下去形成了回调地狱
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>
<script>
// 目标: 获取所有省市区数据
// 1. 获取所有省份列表
axios.get("http://ajax-api.itheima.net/api/province").then((res) => {
// 2. 获取某个省, 对应的城市列表
let pname = res.data.data[16];
axios
.get(`http://ajax-api.itheima.net/api/city?pname=${pname}`)
.then((res) => {
// 3. 获取某个市, 对应的地区列表
let cname = res.data.data[9];
axios
.get(
`http://ajax-api.itheima.net/api/area?pname=${pname}&cname=${cname}`
)
.then((res) => {
console.log(res);
});
});
});
</script>
</body>
</html>
解决方法:Promise链式调用
- 新建html文件, 用axios方法原地返回Promise对象特性
- 用.then()里return Promise对象结果会被链式调用下一个then接收特性
<script>
let pname = "";
axios
.get("http://ajax-api.itheima.net/api/province")
.then((res) => {
// 获取某个省, 对应的城市列表
pname = res.data.data[16];
return axios.get(
`http://ajax-api.itheima.net/api/city?pname=${pname}`
);
})
.then((res) => {
// 获取某个市, 对应的地区列表
let cname = res.data.data[9];
return axios.get(
`http://ajax-api.itheima.net/api/area?pname=${pname}&cname=${cname}`
);
})
.then((res) => {
console.log(res);
}).catch(err => {
console.log('错误');
})
</script>
优化方法:async await语法
async function 函数名() {
const result = await Promise对象
// 拿到Promise对象内成功的结果继续向下执行
}
async function fn() {
const provinces = await axios.get(
"http://ajax-api.itheima.net/api/province"
);
const pname = provinces.data.data[16];
// console.log(pname);
const citys = await axios.get(
`http://ajax-api.itheima.net/api/city?pname=${pname}`
);
// console.log(citys);
const cname = citys.data.data[9];
// console.log(cname);
const areas = await axios.get(
`http://ajax-api.itheima.net/api/area?pname=${pname}&cname=${cname}`
);
// console.log(areas);
return areas.data.data;
}
const t = fn();
console.log(t);