From 4680c50e97d5c62e153ef59e81d1514c9769d8d0 Mon Sep 17 00:00:00 2001 From: ForbesLindesay Date: Thu, 19 Nov 2015 16:31:20 +0000 Subject: [PATCH] Don't allocate an array if no waiting until after resolution --- src/core.js | 17 ++++++++++++----- src/synchronous.js | 3 +++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/core.js b/src/core.js index 30cabbb..4edf797 100644 --- a/src/core.js +++ b/src/core.js @@ -58,9 +58,9 @@ function Promise(fn) { if (typeof fn !== 'function') { throw new TypeError('not a function'); } - this._state = 0; + this._state = -1; this._value = null; - this._deferreds = []; + this._deferreds = null; if (fn === noop) return; doResolve(fn, this); } @@ -86,6 +86,11 @@ function handle(self, deferred) { while (self._state === 3) { self = self._value; } + if (self._state === -1) { + self._state = 0; + self._deferreds = [deferred]; + return; + } if (self._state === 0) { self._deferreds.push(deferred); return; @@ -148,10 +153,12 @@ function reject(self, newValue) { finale(self); } function finale(self) { - for (var i = 0; i < self._deferreds.length; i++) { - handle(self, self._deferreds[i]); + if (self._deferreds) { + for (var i = 0; i < self._deferreds.length; i++) { + handle(self, self._deferreds[i]); + } + self._deferreds = null; } - self._deferreds = null; } function Handler(onFulfilled, onRejected, promise){ diff --git a/src/synchronous.js b/src/synchronous.js index c9f16ed..a30988f 100644 --- a/src/synchronous.js +++ b/src/synchronous.js @@ -44,6 +44,9 @@ Promise.enableSynchronous = function () { if (this._state === 3) { return this._value.getState(); } + if (this._state === -1) { + return 0; + } return this._state; };