前端面试(js异步进阶)

本文探讨了JavaScript的执行顺序,强调同步代码先执行,异步代码后执行。接着讲解了then和catch如何改变Promise状态,以及async函数与Promise的关系——async返回Promise,await类似then,try...catch可替代catch。最后,文章解释了微任务在宏任务之前执行的原理,微任务在DOM渲染前完成,而宏任务则在渲染之后进行。
摘要由CSDN通过智能技术生成

1.js的执行顺序

1.从前到后,一行一行的执行

2.如果某一行代码报错,则停止后面代码的执行

3.先把同步代码执行完,再执行异步

2.then和catch改变状态

then正常返回resolved,里面有报错返回rejected

catch正常返回resolved,里面有报错返回rejected

Promise.resolved().then(()=>{
console.log(1)
}).catch(()=>{
console.log(2)
}).then(()=>{
console.log(3)
})
//1 3

Promise.resolved().then(()=>{
console.log(1)
throw new Error('error1')
}).catch(()=>{
console.log(2)
}).then(()=>{
console.log(3)
})
//1 2 3

Promise.resolved().then(()=>{
console.log(1);
throw new Error('error1')
}).catch(()=>{
console.log(2)
}).catch(()=>{
console.log(3)
})
//1 2 

3.async与promise的关系

async function(){
  const p1=Promise.resolve(200);
  const data=await p1;//await 相当于promise.then
  console.log('data',data);
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值