Skip to content

Commit d252961

Browse files
committed
update promise
1 parent 4272941 commit d252961

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

JS/JS-ch.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,8 @@ Promise 是 ES6 新增的语法,解决了回调地狱的问题。
920920
921921
`then` 函数会返回一个 Promise 实例,并且该返回值是一个新的实例而不是之前的实例。因为 Promise 规范规定除了 `pending` 状态,其他状态是不可以改变的,如果返回的是一个相同实例的话,多个 `then` 调用就失去意义了。
922922
923+
对于 `then` 来说,本质上可以把它看成是 `flatMap`
924+
923925
```js
924926
// 三种状态
925927
const PENDING = "pending";
@@ -936,6 +938,10 @@ function MyPromise(fn) {
936938
_this.rejectedCallbacks = [];
937939

938940
_this.resolve = function (value) {
941+
if (value instanceof MyPromise) {
942+
// 如果 value 是个 Promise,递归执行
943+
return value.then(resolve, reject)
944+
}
939945
setTimeout(() => { // 异步执行,保证执行顺序
940946
if (_this.currentState === PENDING) {
941947
_this.currentState = RESOLVED;

0 commit comments

Comments
 (0)