UNPKG

6.29 kBJavaScriptView Raw
1'use strict';
2
3// Store setTimeout reference so promise-polyfill will be unaffected by
4// other code modifying setTimeout (like sinon.useFakeTimers())
5var setTimeoutFunc = setTimeout;
6
7function noop() {}
8
9// Polyfill for Function.prototype.bind
10function bind(fn, thisArg) {
11 return function() {
12 fn.apply(thisArg, arguments);
13 };
14}
15
16function Promise(fn) {
17 if (!(this instanceof Promise))
18 throw new TypeError('Promises must be constructed via new');
19 if (typeof fn !== 'function') throw new TypeError('not a function');
20 this._state = 0;
21 this._handled = false;
22 this._value = undefined;
23 this._deferreds = [];
24
25 doResolve(fn, this);
26}
27
28function handle(self, deferred) {
29 while (self._state === 3) {
30 self = self._value;
31 }
32 if (self._state === 0) {
33 self._deferreds.push(deferred);
34 return;
35 }
36 self._handled = true;
37 Promise._immediateFn(function() {
38 var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
39 if (cb === null) {
40 (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
41 return;
42 }
43 var ret;
44 try {
45 ret = cb(self._value);
46 } catch (e) {
47 reject(deferred.promise, e);
48 return;
49 }
50 resolve(deferred.promise, ret);
51 });
52}
53
54function resolve(self, newValue) {
55 try {
56 // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
57 if (newValue === self)
58 throw new TypeError('A promise cannot be resolved with itself.');
59 if (
60 newValue &&
61 (typeof newValue === 'object' || typeof newValue === 'function')
62 ) {
63 var then = newValue.then;
64 if (newValue instanceof Promise) {
65 self._state = 3;
66 self._value = newValue;
67 finale(self);
68 return;
69 } else if (typeof then === 'function') {
70 doResolve(bind(then, newValue), self);
71 return;
72 }
73 }
74 self._state = 1;
75 self._value = newValue;
76 finale(self);
77 } catch (e) {
78 reject(self, e);
79 }
80}
81
82function reject(self, newValue) {
83 self._state = 2;
84 self._value = newValue;
85 finale(self);
86}
87
88function finale(self) {
89 if (self._state === 2 && self._deferreds.length === 0) {
90 Promise._immediateFn(function() {
91 if (!self._handled) {
92 Promise._unhandledRejectionFn(self._value);
93 }
94 });
95 }
96
97 for (var i = 0, len = self._deferreds.length; i < len; i++) {
98 handle(self, self._deferreds[i]);
99 }
100 self._deferreds = null;
101}
102
103function Handler(onFulfilled, onRejected, promise) {
104 this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
105 this.onRejected = typeof onRejected === 'function' ? onRejected : null;
106 this.promise = promise;
107}
108
109/**
110 * Take a potentially misbehaving resolver function and make sure
111 * onFulfilled and onRejected are only called once.
112 *
113 * Makes no guarantees about asynchrony.
114 */
115function doResolve(fn, self) {
116 var done = false;
117 try {
118 fn(
119 function(value) {
120 if (done) return;
121 done = true;
122 resolve(self, value);
123 },
124 function(reason) {
125 if (done) return;
126 done = true;
127 reject(self, reason);
128 }
129 );
130 } catch (ex) {
131 if (done) return;
132 done = true;
133 reject(self, ex);
134 }
135}
136
137Promise.prototype['catch'] = function(onRejected) {
138 return this.then(null, onRejected);
139};
140
141Promise.prototype.then = function(onFulfilled, onRejected) {
142 var prom = new this.constructor(noop);
143
144 handle(this, new Handler(onFulfilled, onRejected, prom));
145 return prom;
146};
147
148Promise.prototype['finally'] = function(callback) {
149 var constructor = this.constructor;
150 return this.then(
151 function(value) {
152 return constructor.resolve(callback()).then(function() {
153 return value;
154 });
155 },
156 function(reason) {
157 return constructor.resolve(callback()).then(function() {
158 return constructor.reject(reason);
159 });
160 }
161 );
162};
163
164Promise.all = function(arr) {
165 return new Promise(function(resolve, reject) {
166 if (!arr || typeof arr.length === 'undefined')
167 throw new TypeError('Promise.all accepts an array');
168 var args = Array.prototype.slice.call(arr);
169 if (args.length === 0) return resolve([]);
170 var remaining = args.length;
171
172 function res(i, val) {
173 try {
174 if (val && (typeof val === 'object' || typeof val === 'function')) {
175 var then = val.then;
176 if (typeof then === 'function') {
177 then.call(
178 val,
179 function(val) {
180 res(i, val);
181 },
182 reject
183 );
184 return;
185 }
186 }
187 args[i] = val;
188 if (--remaining === 0) {
189 resolve(args);
190 }
191 } catch (ex) {
192 reject(ex);
193 }
194 }
195
196 for (var i = 0; i < args.length; i++) {
197 res(i, args[i]);
198 }
199 });
200};
201
202Promise.resolve = function(value) {
203 if (value && typeof value === 'object' && value.constructor === Promise) {
204 return value;
205 }
206
207 return new Promise(function(resolve) {
208 resolve(value);
209 });
210};
211
212Promise.reject = function(value) {
213 return new Promise(function(resolve, reject) {
214 reject(value);
215 });
216};
217
218Promise.race = function(values) {
219 return new Promise(function(resolve, reject) {
220 for (var i = 0, len = values.length; i < len; i++) {
221 values[i].then(resolve, reject);
222 }
223 });
224};
225
226// Use polyfill for setImmediate for performance gains
227Promise._immediateFn =
228 (typeof setImmediate === 'function' &&
229 function(fn) {
230 setImmediate(fn);
231 }) ||
232 function(fn) {
233 setTimeoutFunc(fn, 0);
234 };
235
236Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
237 if (typeof console !== 'undefined' && console) {
238 console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
239 }
240};
241
242var global = (function() {
243 // the only reliable means to get the global object is
244 // `Function('return this')()`
245 // However, this causes CSP violations in Chrome apps.
246 if (typeof self !== 'undefined') {
247 return self;
248 }
249 if (typeof window !== 'undefined') {
250 return window;
251 }
252 if (typeof global !== 'undefined') {
253 return global;
254 }
255 throw new Error('unable to locate global object');
256})();
257
258if (!global.Promise) {
259 global.Promise = Promise;
260}