Skip to content

Commit

Permalink
update promise
Browse files Browse the repository at this point in the history
  • Loading branch information
amandakelake committed Apr 7, 2018
1 parent 98ebc03 commit c9b925a
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions JS/JS-en.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,8 @@ Promise can be seen as a state machine and it's initial state is `pending`. We c

The function `then` returns a Promise instance, which is a new instance instead of the previous one. And that's because the Promise specification states that in addition to the `pending` state, other states cannot be changed, and multiple calls of function `then` will be meaningless if the same instance is returned.

For `then`, it can essentially be seen as `flatMap`

```js
// three states
const PENDING = 'pending';
Expand All @@ -242,6 +244,10 @@ function MyPromise(fn) {
_this.resolve = function(value) {
// execute asynchronously to guarantee the execution order
setTimeout(() => {
if (value instanceof MyPromise) {
// if value is a Promise, execute recursively
return value.then(_this.resolve, _this.reject)
}
if (_this.currentState === PENDING) {
_this.currentState = RESOLVED;
_this.value = value;
Expand Down

0 comments on commit c9b925a

Please sign in to comment.