From ee5336623e1152e15295c9c3dea7b6f030e0caba Mon Sep 17 00:00:00 2001 From: share Date: Sun, 12 Jan 2020 15:07:07 +0800 Subject: [PATCH] Fix - do not change status & value when fulfilled / rejected Refer: 1. https://promisesaplus.com/#point-14 2. https://promisesaplus.com/#point-17 --- dist/src/promise.js | 10 ++++++++++ src/promise.js | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/dist/src/promise.js b/dist/src/promise.js index bf0870b..9f6d807 100644 --- a/dist/src/promise.js +++ b/dist/src/promise.js @@ -27,7 +27,13 @@ class Promise { executor(this._resolve.bind(this), this._reject.bind(this)); } + _hasResolved() { + return this._isFulfilled() || this._isRejected(); + } + _resolve(x) { + if (this._hasResolved()) return; + if (x === this) { throw new TypeError("Resolving object can not be the same object"); } else if (x instanceof Promise) { @@ -58,12 +64,16 @@ class Promise { } _fulfill(result) { + if (this._hasResolved()) return; + this._state = State.Fulfilled; this._value = result; this._handlers.forEach(handler => this._callHandler(handler)); } _reject(error) { + if (this._hasResolved()) return; + this._state = State.Rejected; this._value = error; this._handlers.forEach(handler => this._callHandler(handler)); diff --git a/src/promise.js b/src/promise.js index 774e0c8..0c12fbe 100644 --- a/src/promise.js +++ b/src/promise.js @@ -22,7 +22,13 @@ export class Promise { executor(this._resolve.bind(this), this._reject.bind(this)); } + _hasResolved() { + return this._isFulfilled() || this._isRejected() + } + _resolve(x) { + if (this._hasResolved()) return + if (x === this) { throw new TypeError("Resolving object can not be the same object"); } else if (x instanceof Promise) { @@ -57,12 +63,16 @@ export class Promise { } _fulfill(result) { + if (this._hasResolved()) return + this._state = State.Fulfilled; this._value = result; this._handlers.forEach(handler => this._callHandler(handler)); } _reject(error) { + if (this._hasResolved()) return + this._state = State.Rejected; this._value = error; this._handlers.forEach(handler => this._callHandler(handler));