Skip to content

Commit

Permalink
update: 3.1 Promise 的题目三添加两个例子
Browse files Browse the repository at this point in the history
  • Loading branch information
nswbmw committed Aug 25, 2018
1 parent 5ca031a commit 2fd41a3
Showing 1 changed file with 60 additions and 4 deletions.
64 changes: 60 additions & 4 deletions 3.1 Promise.md
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,62 @@ then: success1

**解释**:构造函数中的 resolve 或 reject 只有在第 1 次执行时有效,多次调用没有任何作用,再次印证代码二的结论:promise 状态一旦改变则不能再变。

再看两个例子:

```js
const promise = new Promise((resolve, reject) => {
console.log(1)
return Promise.reject(new Error('haha'))
})
promise.then((res) => {
console.log(2, res)
}).catch((err) => {
console.error(3, err)
})
console.log(4)
console.log(promise)
```

运行结果:

```
1
4
Promise { <pending> }
(node:22493) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: haha
(node:22493) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
```

```js
const promise = new Promise((resolve, reject) => {
console.log(1)
throw new Error('haha')
})
promise.then((res) => {
console.log(2, res)
}).catch((err) => {
console.error(3, err)
})
console.log(4)
console.log(promise)
```

运行结果:

```
1
4
Promise {
<rejected> Error: haha
at Promise (/Users/nswbmw/Desktop/test/app.js:6:9)
...
3 Error: haha
at Promise (/Users/nswbmw/Desktop/test/app.js:6:9)
...
```

**解释**:构造函数内只能通过调用 resolve(pending->fullfiled) 或者 reject(pending->rejected) 或者 throw 一个 error(pending->rejected) 改变状态。所以第一个例子的 promise 状态是 pending,也就不会调用 .then/.catch。

### 题目四

```js
Expand Down Expand Up @@ -911,13 +967,13 @@ Promise.resolve()
### 题目十

```js
process.nextTick(() => {
console.log('nextTick')
})
Promise.resolve()
.then(() => {
console.log('then')
})
process.nextTick(() => {
console.log('nextTick')
})
setImmediate(() => {
console.log('setImmediate')
})
Expand All @@ -933,7 +989,7 @@ then
setImmediate
```

**解释**:process.nextTick 和 promise.then 都属于 microtask,而 setImmediate 属于 macrotask,在事件循环的 check 阶段执行。事件循环的每个阶段(macrotask)之间都会执行 microtask,以上代码本身(macrotask)在执行完后会执行一次 microtask。
**解释**:process.nextTick 和 promise.then 都属于 microtask(但 process.nextTick 的优先级大于 promise.then),而 setImmediate 属于 macrotask,在事件循环的 check 阶段执行。事件循环的每个阶段(macrotask)之间都会执行 microtask,以上代码本身(macrotask)在执行完后会执行一次 microtask。

## 3.1.12 参考链接

Expand Down

0 comments on commit 2fd41a3

Please sign in to comment.