准备知识
代码举例
举例 1:宏任务和微任务的执行顺序
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| setTimeout(() => { console.log('setTimeout'); }, 0);
new Promise((resolve, reject) => { resolve(); console.log('promise1'); }).then((res) => { console.log('promise then'); });
console.log('qianguyihao');
|
打印结果:
1 2 3 4
| promise1 qianguyihao promise then setTimeout
|
上方代码执行的顺序依次是:同步任务 –> 微任务 –> 宏任务。
举例 2:宏任务和微任务的嵌套
1 2 3 4 5 6 7 8 9 10 11 12
| new Promise((resolve, reject) => { setTimeout(() => { resolve(); console.log('setTimeout'); }, 0); console.log('promise1'); }).then((res) => { console.log('promise then'); });
console.log('qianguyihao');
|
打印结果:
1 2 3 4
| promise1 qianguyihao setTimeout promise then
|
上方代码解释:在执行宏任务的过程中,创建了一个微任务。但是需要先把当前这个宏任务执行完,再去创建并执行微任务。