Skip to content

Commit

Permalink
异步
Browse files Browse the repository at this point in the history
  • Loading branch information
yihan12 committed Sep 1, 2023
1 parent a2a4e55 commit 4198624
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 1 deletion.
2 changes: 2 additions & 0 deletions javascript/异步/Promise.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ pending->resolved 或者 pending->rejected

then 正常回调返回 resolved,如果有报错则返回 rejected
catch 正常回调返回 resolved,如果有报错返回 rejected

#
7 changes: 7 additions & 0 deletions javascript/异步/handwriting Promise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Promise A+ 规范

# 手写基本要求

- 初始化&异步调用
- then、catch 链式调用
- API .resolve .reject .all .race,
43 changes: 43 additions & 0 deletions javascript/异步/microtask&macrotaskmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# DOM 渲染和 Event Loop

1. Call Stack 空闲
2. 尝试 DOM 渲染
3. 触发 Event Loop

- 每次 Call Stack 清空(即每次轮询结束),即同步任务执行完
- 都是 DOM 渲染的机会,DOM 结构如果有任何改变则重新渲染。
- 然后再次触发 Event Loop

# 宏任务

DOM 渲染后触发:如 setTimeout

# 微任务

DOM 渲染前触发: 如 Promise

# 从 Event Loop 解释,为什么微任务执行更早

1. 执行 Promise
2. 但是不会经过 Web APIs。因为 Promise 是 ES 规范,不是 W3C 规范
3. 不像 setTimeout 在 Web APIs 等待实际,在 DOM 渲染后放到 CallBack queue(宏任务队列) 中。
4. Promise 会在 micro task queue(微任务队列)

整个执行步骤:

1. Call Stack 清空
2. 放在微任务队列中(micro task queue),执行当前微任务
3. 尝试 DOM 渲染。
4. 触发 Event Loop

# 宏任务有哪些?微任务有哪些?为什么微任务触发时间更早

宏任务: setTimeout、 setInteral、Ajax、DOM 事件

微任务: Promise、async/await

微任务比宏任务执行时间更早

# 宏任务、微任务和 DOM 渲染的关系

# 宏任务、微任务和 DOM 渲染,在 Event Loop 的过程
31 changes: 30 additions & 1 deletion javascript/异步/异步.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,35 @@
- js 异步要基于回调来实现
- event loop 是异步回调的原理

# 什么是宏任务,微任务。两者有什么区别?
### Event Loop 过程 1

1. 同步代码,一行一行放到 Call Stack 执行
2. 异步代码,会记录下来,等待时机(定时,网络请求)
3. 时机到了,移到 CallBack queue 中。

### Event Loop 过程 2

4. 如何 Call Stack 为空(即同步代码执行完),Event Loop 开始工作
5. 轮询查找 CallBack queue,如果有则移到 Call Stack 中执行
6. 然后继续轮询查找(永动机一样)

# Promise 有哪三种状态,如何变化?

# DOM 事件和 Event Loop

- JS 是单线程的
- 异步(setTimeout、Ajax 等)使用回调,基于 Event Loop
- DOM 事件也使用回调,基于 Event Loop

# Promise 进阶

- 三种状态,状态的表现和变化
- then 和 catch 对状态的影响
- then 和 catch 的链式调用

# async/await

- async/await 解决了异步回调是一个很香的语法糖
- async/await 和 Promise 的关系

# 什么是宏任务,微任务。两者有什么区别?

0 comments on commit 4198624

Please sign in to comment.