前端面试:promise...then与asnyc ...await
JavaScript是单线程,没有异步编程的概念,浏览器 / Node 提供了 异步 API(比如定时器、网络请求) 。为了让代码 “不阻塞”,早期用 回调函数 处理异步结果,我们可以通过函数回调机制来实现异步编程。
promise...then...链式调用避免层层嵌套。async...await是Promise 的语法糖,让异步代码更简洁、读起来更像同步,本质还是依赖 Promise。
实际开发中,建议优先用 async/await
(简洁)。
<script>function one() {console.log('回到宿舍先开空调')}function two() {console.log('打卡欧阳春晓锻炼20分钟')}function three() {console.log('洗澡睡觉')}const P1 = new Promise((resolve, reject) => {resolve('回到宿舍')})P1.then(result1 => {console.log(result1)}).then(() => {one();}).then(() => {two();}).then(()=>{three();}).catch(()=>{console.log('先回自习室拿手机'')})
</script>
<script>function one() {console.log('回到宿舍先开空调')}function two() {console.log('打卡欧阳春晓锻炼20分钟')}function three() {console.log('洗澡睡觉')}const P1 = new Promise((resolve, reject) => {resolve('回到宿舍')})async function HH() {try {const result = await P1;console.log(result)one();two();three();} catch (error) {console.log('先回自习室拿手机'')}}HH();</script>
<script>const P1 = new Promise((resolve, reject) => {resolve('回到宿舍')})const P2 = new Promise((resolve, reject) => {resolve('回到宿舍先开空调')})const P3 = new Promise((resolve, reject) => {resolve('打卡欧阳春晓锻炼20分钟')})const P4 = new Promise((resolve, reject) => {resolve('洗澡睡觉')})async function HH() {try {const [result1,result2,result3,result4] = await Promise.all([P1,P2,P3,P4]);console.log(result1,result2,result3,result4);} catch (error) {console.log('先回自习室拿手机')}}HH();</script>