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);
}
async function(){
const data1=await 400;//相当于Promise.resolve(400)
console.log('data1',data1);
}
async function(){
const data2=await fn1();
console.log('data2',data2);
}
总结:
执行async函数,返回的是promise对象
await相当于promise的then
try...catch可捕获异常,代替了promise的catch
4.为什么微任务执行比宏任务执行的更早?
微任务在dom渲染前触发,宏任务在dom渲染后触发
const $p1=$('<p>一段文字</p>');
const $p2=$('<p>一段文字</p>');
const $p3=$('<p>一段文字</p>');
$('#container')
.append($p1)
.append($p2)
.append($p3)
Promise.resolve().then(()=>{
console.log('length1',$('#container').children().length)
alert('微任务在dom渲染前执行')
})
Settimeout(()=>{
console.log('length2',$('#container').children().length)
alert('宏任务在dom渲染后执行')
})
本文探讨了JavaScript的执行顺序,强调同步代码先执行,异步代码后执行。接着讲解了then和catch如何改变Promise状态,以及async函数与Promise的关系——async返回Promise,await类似then,try...catch可替代catch。最后,文章解释了微任务在宏任务之前执行的原理,微任务在DOM渲染前完成,而宏任务则在渲染之后进行。
639

被折叠的 条评论
为什么被折叠?



