你可以的,去飞吧!
同步代码和异步代码
回调函数地狱和 Promise 链式调用
回调函数地狱
缔造“回调地狱”↓
制造里层回调错误,却在最外层接收错误→无法捕获
axios源码抛出异常(未捕获)
<!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>回调地狱</title>
</head><body><form><span>省份:</span><select><option class="province"></option></select><span>城市:</span><select><option class="city"></option></select><span>地区:</span><select><option class="area"></option></select></form><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>/*** 目标:演示回调函数地狱* 需求:获取默认第一个省,第一个市,第一个地区并展示在下拉菜单中* 概念:在回调函数中嵌套回调函数,一直嵌套下去就形成了回调函数地狱* 缺点:可读性差,异常无法获取,耦合性严重,牵一发动全身*/// 1. 获取默认第一个省份的名字axios({url: 'http://hmajax.itheima.net/api/province'}).then(result => {const pname = result.data.list[0]document.querySelector('.province').innerHTML = pname// 2. 获取默认第一个城市的名字axios({url: 'http://hmajax.itheima.net/api/city', params: { pname }}).then(result => {const cname = result.data.list[0]document.querySelector('.city').innerHTML = cname// 3. 获取默认第一个地区的名字axios({url: 'http://hmajax.itheima.net/api/area', params: { pname, cname }}).then(result => {console.log(result)const areaName = result.data.list[0]document.querySelector('.area').innerHTML = areaName})})}).catch(error => {console.dir(error)})</script>
</body></html>
总结:
Promise - 链式调用
实操:
<!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>Promise_链式调用</title>
</head><body><script>/*** 目标:掌握Promise的链式调用* 需求:把省市的嵌套结构,改成链式调用的线性结构*/// 1. 创建Promise对象-模拟请求省份名字const p = new Promise((resolve, reject) => {setTimeout(() => {resolve('北京市')}, 2000)})// 2. 获取省份名字const p2 = p.then(result => {console.log(result)// 3. 创建Promise对象-模拟请求城市名字// return Promise对象最终状态和结果,影响到新的Promise对象return new Promise((resolve, reject) => {setTimeout(() => {resolve(result + '--- 北京')}, 2000)})})// 4. 获取城市名字p2.then(result => {console.log(result)})// then()原地的结果是一个新的Promise对象console.log(p2 === p)</script>
</body></html>
总结:
async 和 await 使用
使用方法
在async函数中使用await直接获取Promise对象成功状态的结果值
完整代码:
<!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>async函数和await_解决回调函数地狱</title>
</head><body><form><span>省份:</span><select><option class="province"></option></select><span>城市:</span><select><option class="city"></option></select><span>地区:</span><select><option class="area"></option></select></form><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>/*** 目标:掌握async和await语法,解决回调函数地狱* 概念:在async函数内,使用await关键字,获取Promise对象"成功状态"结果值* 注意:await必须用在async修饰的函数内(await会阻止"异步函数内"代码继续执行,原地等待结果)*/// 1. 定义async修饰函数async function getData() {// 2. await等待Promise对象成功的结果const pObj = await axios({url: 'http://hmajax.itheima.net/api/province'})const pname = pObj.data.list[0]const cObj = await axios({url: 'http://hmajax.itheima.net/api/city', params: { pname }})const cname = cObj.data.list[0]const aObj = await axios({url: 'http://hmajax.itheima.net/api/area', params: { pname, cname }})const areaName = aObj.data.list[0]document.querySelector('.province').innerHTML = pnamedocument.querySelector('.city').innerHTML = cnamedocument.querySelector('.area').innerHTML = areaName}getData()</script>
</body></html>
async函数和await_捕获错误
在area后面加了“1”,用comsole.dir打印错误信息,
接口返回的,真正的响应数据在错误对象(该对象中有着axios处理过的提供的一些其他信息)的response属性
还可以到网络里查看到
疑问:省份和城市应该获取成功,为什么没有展示?
——在try语句中,如果某句代码发生错误,后面的不会再执行。
<!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>async函数和await_错误捕获</title>
</head><body><form><span>省份:</span><select><option class="province"></option></select><span>城市:</span><select><option class="city"></option></select><span>地区:</span><select><option class="area"></option></select></form><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>/*** 目标:async和await_错误捕获*/async function getData() {// 1. try包裹可能产生错误的代码try {const pObj = await axios({ url: 'http://hmajax.itheima.net/api/province' })const pname = pObj.data.list[0]const cObj = await axios({ url: 'http://hmajax.itheima.net/api/city', params: { pname } })const cname = cObj.data.list[0]const aObj = await axios({ url: 'http://hmajax.itheima.net/api/area', params: { pname, cname } })const areaName = aObj.data.list[0]document.querySelector('.province').innerHTML = pnamedocument.querySelector('.city').innerHTML = cnamedocument.querySelector('.area').innerHTML = areaName} catch (error) {// 2. 接着调用catch块,接收错误信息// 如果try里某行代码报错后,try中剩余的代码不会执行了console.dir(error)}}getData()</script>
</body></html>
事件循环-EventLoop
事件循环
运行结果都是1 3 2
调用栈:可以理解为 JS代码在运行时形成的调用环境
宿主环境:浏览器(注意:浏览器是多线程的,JS是单线程的)
任务队列:内存开辟的一块空间
代码及答案:
<!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>事件循环_练习</title>
</head><body><script>/*** 目标:阅读并回答执行的顺序结果*/console.log(1)setTimeout(() => {console.log(2)}, 0)function myFn() {console.log(3)}function ajaxFn() {const xhr = new XMLHttpRequest()xhr.open('GET', 'http://hmajax.itheima.net/api/province')xhr.addEventListener('loadend', () => {console.log(4)})xhr.send()}for (let i = 0; i < 1; i++) {console.log(5)}ajaxFn()document.addEventListener('click', () => {console.log(6)})myFn()// 1 5 3 2 4 点击一次document就会执行一次打印6</script>
</body></html>
宏任务与微任务
宏任务与微任务 - 执行顺序
什么是宏任务
——交给浏览器管理和执行的异步代码
什么是微任务(在JS引擎中执行,先与宏任务执行)
——JS引擎发起和管理执行的异步代码
经典面试题
<!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>事件循环经典_经典面试题</title>
</head><body><script>// 目标:回答代码执行顺序console.log(1)setTimeout(() => {console.log(2)const p = new Promise(resolve => resolve(3))p.then(result => console.log(result))}, 0)const p = new Promise(resolve => {setTimeout(() => {console.log(4)}, 0)resolve(5)})p.then(result => console.log(result))const p2 = new Promise(resolve => resolve(6))p2.then(result => console.log(result))console.log(7)// 1 7 5 6 2 3 4</script></body></html>
Promise.all 静态方法
合并多个Promise对象:
展出数据,可使用低速网络查看是否同时展示
测试catch,在weather后面加123
进catch不进then
案例 - 商品分类
<!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>案例_分类导航</title><link rel="stylesheet" href="./css/index.css">
</head><body><!-- 大容器 --><div class="container"><div class="sub-list"><div class="item"><h3>分类名字</h3><ul><li><a href="javascript:;"><img src="http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/img/category%20(9).png" /><p>巧克力</p></a></li><li><a href="javascript:;"><img src="http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/img/category%20(9).png" /><p>巧克力</p></a></li><li><a href="javascript:;"><img src="http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/img/category%20(9).png" /><p>巧克力</p></a></li></ul></div></div></div><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>/*** 目标:把所有商品分类“同时”渲染到页面上* 1. 获取所有一级分类数据* 2. 遍历id,创建获取二级分类请求* 3. 合并所有二级分类Promise对象* 4. 等待同时成功后,渲染页面*/// 1. 获取所有一级分类数据axios({url: 'http://hmajax.itheima.net/api/category/top'}).then(result => {console.log(result)// 2. 遍历id,创建获取二级分类请求const secPromiseList = result.data.data.map(item => {return axios({url: 'http://hmajax.itheima.net/api/category/sub',params: {id: item.id // 一级分类id}})})console.log(secPromiseList) // [二级分类请求Promise对象,二级分类请求Promise对象,...]// 3. 合并所有二级分类Promise对象const p = Promise.all(secPromiseList)p.then(result => {console.log(result)// 4. 等待同时成功后,渲染页面const htmlStr = result.map(item => {const dataObj = item.data.data // 取出关键数据对象return `<div class="item"><h3>${dataObj.name}</h3><ul>${dataObj.children.map(item => {return `<li><a href="javascript:;"><img src="${item.picture}"><p>${item.name}</p></a></li>`}).join('')}</ul></div>`}).join('')console.log(htmlStr)document.querySelector('.sub-list').innerHTML = htmlStr})})</script>
</body></html>
效果:先是默认的HTML结构,全部请求完成后才重新渲染展示如下
案例 - 学习反馈
样式结构:
<!DOCTYPE html>
<html lang="zh-CN"><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"><!-- 初始化样式 --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reset.css@2.0.2/reset.min.css"><!-- 引入bootstrap.css --><link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet"><!-- 核心样式 --><link rel="stylesheet" href="./css/index.css"><title>学习反馈</title>
</head><body><div class="container"><h4 class="stu-title">学习反馈</h4><img class="bg" src="./img/head.png" alt=""><div class="item-wrap"><div class="hot-area"><span class="hot">热门校区</span><ul class="nav"><li><a target="_blank" href="http://bjcp.itheima.com/">北京</a> </li><li><a target="_blank" href="http://sh.itheima.com/">上海</a> </li><li><a target="_blank" href="http://gz.itheima.com/">广州</a> </li><li><a target="_blank" href="http://sz.itheima.com/">深圳</a> </li></ul></div><form class="info-form"><div class="area-box"><span class="title">地区选择</span><select name="province" class="province"><option value="">省份</option></select><select name="city" class="city"><option value="">城市</option></select><select name="area" class="area"><option value="">地区</option></select></div><div class="area-box"><span class="title">您的称呼</span><input type="text" name="nickname" class="nickname" value="播仔"></div><div class="area-box"><span class="title">宝贵建议</span><textarea type="text" name="feedback" class="feedback" placeholder="您对AJAX阶段课程宝贵的建议"></textarea></div><div class="area-box"><button type="button" class="btn btn-secondary submit">确定提交</button></div></form></div></div><script src="https://cdn.bootcdn.net/ajax/libs/axios/1.2.0/axios.min.js"></script><script src="./js/form-serialize.js"></script><!-- 核心代码 --><script src="./js/index.js"></script>
</body></html>
功能核心JS代码:
/*** 目标1:完成省市区下拉列表切换* 1.1 设置省份下拉菜单数据* 1.2 切换省份,设置城市下拉菜单数据,清空地区下拉菜单* 1.3 切换城市,设置地区下拉菜单数据*/
// 1.1 设置省份下拉菜单数据
axios({url: 'http://hmajax.itheima.net/api/province'
}).then(result => {const optionStr = result.data.list.map(pname => `<option value="${pname}">${pname}</option>`).join('')document.querySelector('.province').innerHTML = `<option value="">省份</option>` + optionStr
})// 1.2 切换省份,设置城市下拉菜单数据,清空地区下拉菜单
document.querySelector('.province').addEventListener('change', async e => {// 获取用户选择省份名字// console.log(e.target.value)const result = await axios({ url: 'http://hmajax.itheima.net/api/city', params: { pname: e.target.value } })const optionStr = result.data.list.map(cname => `<option value="${cname}">${cname}</option>`).join('')// 把默认城市选项+下属城市数据插入select中document.querySelector('.city').innerHTML = `<option value="">城市</option>` + optionStr// 清空地区数据document.querySelector('.area').innerHTML = `<option value="">地区</option>`
})// 1.3 切换城市,设置地区下拉菜单数据
document.querySelector('.city').addEventListener('change', async e => {console.log(e.target.value)const result = await axios({url: 'http://hmajax.itheima.net/api/area', params: {pname: document.querySelector('.province').value,cname: e.target.value}})console.log(result)const optionStr = result.data.list.map(aname => `<option value="${aname}">${aname}</option>`).join('')console.log(optionStr)document.querySelector('.area').innerHTML = `<option value="">地区</option>` + optionStr
})/*** 目标2:收集数据提交保存* 2.1 监听提交的点击事件* 2.2 依靠插件收集表单数据* 2.3 基于axios提交保存,显示结果*/
// 2.1 监听提交的点击事件
document.querySelector('.submit').addEventListener('click', async () => {// 2.2 依靠插件收集表单数据const form = document.querySelector('.info-form')const data = serialize(form, { hash: true, empty: true })console.log(data)// 2.3 基于axios提交保存,显示结果try {const result = await axios({url: 'http://hmajax.itheima.net/api/feedback',method: 'POST',data})console.log(result)alert(result.data.message)} catch (error) {console.dir(error)alert(error.response.data.message)}
})
效果: