一、setTimeout嵌套
setTimeout(()=>{
console.log(1);
},0)
setTimeout(()=>{
console.log(2);
setTimeout(()=>{
console.log(3);
})
},0)
</script>
此时输出: 1 2 3
图解:
二、promise嵌套
<script>
new Promise(function(reslove,reject){
console.log(1);
reslove(2);
}).then(function(data){
console.log(data);
new Promise(function(reslove,reject){
console.log(6);
reslove(7)
}).then(function(data){
console.log(data);
})
}).catch(function(error){
console.log(error);
})
new Promise (function(reslove,reject){
console.log(4);
reject(5)
}).catch(function(data){
console.log(data);
})
</script>
图解:
step1: 首先执行同步代码 打印 1 4
step2: 来到第一个Promise下的then 打印 2 进入到第一个primise下嵌套的promise,先打印同步代码6,同时出现了一个then微任务,将其添加至script标签宏任务。此时已经执行完第一个.then微任务
step3: 接着执行.catch微任务 打印5 此时.catch微任务完成
step4: 执行第一个primise嵌套的promise下的then微任务,打印7 此时微任务全部执行完毕
输出:
3.setTimeout与promise混合
<script>
setTimeout(()=>{
console.log(0);
},0)
new Promise(function(reslove,reject){
console.log(1);
reslove(2);
reject(3)
}).then(function(data){
console.log(data);
setTimeout(()=>{
console.log(6);
new Promise(function(reslove,reject){
console.log(10);
reslove(11)
}).then(function(data){
console.log(data);
})
},0)
new Promise(function(reslove,reject){
console.log(4);
reslove(5)
}).then(function(data){
console.log(data);
})
}).catch(function(error){
console.log(error);
})
new Promise (function(reslove,reject){
console.log(8);
reslove(9)
}).then(function(data){
console.log(data);
})
</script>
step1: 推入第一个settimeout宏任务 ,运行同步代码 1 8 遇到then微任务则挂起 此时script标签宏任务中的同步代码以及完成。
step2: 来到第一个then 打印2 之后 发现第二个settimeout宏任务,将其挂起,推入消息队列中,往下执行,遇到了promise,先执行同步代码 打印 4 ,此时第一个then微任务已经执行完毕。将其弹出,执行第二个then微任务,
step3: 打印完9之后 将第二个then微任务弹出
step4: 执行第三个then微任务 打印出 5 此时执行script标签宏任务全部完成 ,紧接着执行 第一个settimeout宏任务
step5: 推入第一个settimeout宏任务 打印 0 结束后将其弹出 执行第二个settimeout宏函数 打印 6 10
step6: 第二个settimeout宏任务中 遇到.then微任务 打印11
输出: