Web/06-JavaScript基础:异步编程/08-宏任务和微任务.md
2021-10-30 15:15:23 +08:00

75 lines
1.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 09-宏任务和微任务
publish: true
---
<ArticleTopAd></ArticleTopAd>
## 准备知识
- 在执行一个 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
```
上方代码解释在执行宏任务的**过程中**创建了一个微任务但是需要**先把当前这个宏任务执行完**再去**创建并执行**微任务