2021-07-29 11:08:52 +08:00
|
|
|
|
---
|
|
|
|
|
title: 09-宏任务和微任务
|
|
|
|
|
publish: true
|
|
|
|
|
---
|
|
|
|
|
|
|
|
|
|
<ArticleTopAd></ArticleTopAd>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2021-05-27 21:56:03 +08:00
|
|
|
|
## 准备知识
|
|
|
|
|
|
|
|
|
|
- 在执行一个 Promise 对象的时候,当走完`resolve();`之后,就会立刻把 `.then()`里面的代码加入到**微任务队列**当中。
|
|
|
|
|
|
|
|
|
|
- 任务的一般执行顺序:**同步任务 --> 微任务 --> 宏任务**。
|
|
|
|
|
|
|
|
|
|
## 代码举例
|
|
|
|
|
|
|
|
|
|
### 举例 1:宏任务和微任务的执行顺序
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
// 宏任务
|
|
|
|
|
console.log('setTimeout');
|
|
|
|
|
}, 0);
|
|
|
|
|
|
|
|
|
|
new Promise((resolve, reject) => {
|
|
|
|
|
resolve();
|
|
|
|
|
console.log('promise1'); // 同步任务
|
|
|
|
|
}).then((res) => {
|
|
|
|
|
// 微任务
|
|
|
|
|
console.log('promise then');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
console.log('qianguyihao'); // 同步任务
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
打印结果:
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
promise1
|
|
|
|
|
qianguyihao
|
|
|
|
|
promise then
|
|
|
|
|
setTimeout
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
上方代码执行的顺序依次是:**同步任务 --> 微任务 --> 宏任务**。
|
|
|
|
|
|
|
|
|
|
### 举例 2:宏任务和微任务的嵌套
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
new Promise((resolve, reject) => {
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
resolve();
|
|
|
|
|
console.log('setTimeout');
|
|
|
|
|
}, 0);
|
|
|
|
|
console.log('promise1');
|
|
|
|
|
}).then((res) => {
|
|
|
|
|
// 微任务
|
|
|
|
|
console.log('promise then');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
console.log('qianguyihao');
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
打印结果:
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
promise1
|
|
|
|
|
qianguyihao
|
|
|
|
|
setTimeout
|
|
|
|
|
promise then
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
上方代码解释:在执行宏任务的**过程中**,创建了一个微任务。但是需要**先把当前这个宏任务执行完**,再去轮询异步任务的队列,进而执行微任务。
|