09-宏任务和微任务
准备知识
在执行一个 Promise 对象的时候,当走完
resolve();之后,就会立刻把.then()里面的代码加入到微任务队列当中。任务的一般执行顺序:同步任务 —> 微任务 —> 宏任务。
代码举例
举例 1:宏任务和微任务的执行顺序
setTimeout(() => {// 宏任务console.log('setTimeout');}, 0);new Promise((resolve, reject) => {resolve();console.log('promise1'); // 同步任务}).then((res) => {// 微任务console.log('promise then');});console.log('qianguyihao'); // 同步任务
打印结果:
promise1qianguyihaopromise thensetTimeout
上方代码执行的顺序依次是:同步任务 —> 微任务 —> 宏任务。
举例 2:宏任务和微任务的嵌套
new Promise((resolve, reject) => {setTimeout(() => {resolve();console.log('setTimeout'); // 宏任务}, 0);console.log('promise1');}).then((res) => {// 微任务console.log('promise then');});console.log('qianguyihao');
打印结果:
promise1qianguyihaosetTimeoutpromise then
上方代码解释:在执行宏任务的过程中,创建了一个微任务。但是需要先把当前这个宏任务执行完,再去创建并执行微任务。
