Debian Codegraph @

closure-library/closure/goog/promise/promise.js

raw
1 // Copyright 2013 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 goog.provide('goog.Promise');
16
17 goog.require('goog.Thenable');
18 goog.require('goog.asserts');
19 goog.require('goog.async.FreeList');
20 goog.require('goog.async.run');
21 goog.require('goog.async.throwException');
22 goog.require('goog.debug.Error');
23 goog.require('goog.promise.Resolver');
24
25
26
27 /**
28 * NOTE: This class was created in anticipation of the built-in Promise type
29 * being standardized and implemented across browsers. Now that Promise is
30 * available in modern browsers, and is automatically polyfilled by the Closure
31 * Compiler, by default, most new code should use native {@code Promise}
32 * instead of {@code goog.Promise}. However, {@code goog.Promise} has the
33 * concept of cancellation which native Promises do not yet have. So code
34 * needing cancellation may still want to use {@code goog.Promise}.
35 *
36 * Promises provide a result that may be resolved asynchronously. A Promise may
37 * be resolved by being fulfilled with a fulfillment value, rejected with a
38 * rejection reason, or blocked by another Promise. A Promise is said to be
39 * settled if it is either fulfilled or rejected. Once settled, the Promise
40 * result is immutable.
41 *
42 * Promises may represent results of any type, including undefined. Rejection
43 * reasons are typically Errors, but may also be of any type. Closure Promises
44 * allow for optional type annotations that enforce that fulfillment values are
45 * of the appropriate types at compile time.
46 *
47 * The result of a Promise is accessible by calling {@code then} and registering
48 * {@code onFulfilled} and {@code onRejected} callbacks. Once the Promise
49 * is settled, the relevant callbacks are invoked with the fulfillment value or
50 * rejection reason as argument. Callbacks are always invoked in the order they
51 * were registered, even when additional {@code then} calls are made from inside
52 * another callback. A callback is always run asynchronously sometime after the
53 * scope containing the registering {@code then} invocation has returned.
54 *
55 * If a Promise is resolved with another Promise, the first Promise will block
56 * until the second is settled, and then assumes the same result as the second
57 * Promise. This allows Promises to depend on the results of other Promises,
58 * linking together multiple asynchronous operations.
59 *
60 * This implementation is compatible with the Promises/A+ specification and
61 * passes that specification's conformance test suite. A Closure Promise may be
62 * resolved with a Promise instance (or sufficiently compatible Promise-like
63 * object) created by other Promise implementations. From the specification,
64 * Promise-like objects are known as "Thenables".
65 *
66 * @see http://promisesaplus.com/
67 *
68 * @param {function(
69 * this:RESOLVER_CONTEXT,
70 * function((TYPE|IThenable<TYPE>|Thenable)=),
71 * function(*=)): void} resolver
72 * Initialization function that is invoked immediately with {@code resolve}
73 * and {@code reject} functions as arguments. The Promise is resolved or
74 * rejected with the first argument passed to either function.
75 * @param {RESOLVER_CONTEXT=} opt_context An optional context for executing the
76 * resolver function. If unspecified, the resolver function will be executed
77 * in the default scope.
78 * @constructor
79 * @struct
80 * @final
81 * @implements {goog.Thenable<TYPE>}
82 * @template TYPE,RESOLVER_CONTEXT
83 */
84 goog.Promise = function(resolver, opt_context) {
85 /**
86 * The internal state of this Promise. Either PENDING, FULFILLED, REJECTED, or
87 * BLOCKED.
88 * @private {goog.Promise.State_}
89 */
90 this.state_ = goog.Promise.State_.PENDING;
91
92 /**
93 * The settled result of the Promise. Immutable once set with either a
94 * fulfillment value or rejection reason.
95 * @private {*}
96 */
97 this.result_ = undefined;
98
99 /**
100 * For Promises created by calling {@code then()}, the originating parent.
101 * @private {goog.Promise}
102 */
103 this.parent_ = null;
104
105 /**
106 * The linked list of {@code onFulfilled} and {@code onRejected} callbacks
107 * added to this Promise by calls to {@code then()}.
108 * @private {?goog.Promise.CallbackEntry_}
109 */
110 this.callbackEntries_ = null;
111
112 /**
113 * The tail of the linked list of {@code onFulfilled} and {@code onRejected}
114 * callbacks added to this Promise by calls to {@code then()}.
115 * @private {?goog.Promise.CallbackEntry_}
116 */
117 this.callbackEntriesTail_ = null;
118
119 /**
120 * Whether the Promise is in the queue of Promises to execute.
121 * @private {boolean}
122 */
123 this.executing_ = false;
124
125 if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {
126 /**
127 * A timeout ID used when the {@code UNHANDLED_REJECTION_DELAY} is greater
128 * than 0 milliseconds. The ID is set when the Promise is rejected, and
129 * cleared only if an {@code onRejected} callback is invoked for the
130 * Promise (or one of its descendants) before the delay is exceeded.
131 *
132 * If the rejection is not handled before the timeout completes, the
133 * rejection reason is passed to the unhandled rejection handler.
134 * @private {number}
135 */
136 this.unhandledRejectionId_ = 0;
137 } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {
138 /**
139 * When the {@code UNHANDLED_REJECTION_DELAY} is set to 0 milliseconds, a
140 * boolean that is set if the Promise is rejected, and reset to false if an
141 * {@code onRejected} callback is invoked for the Promise (or one of its
142 * descendants). If the rejection is not handled before the next timestep,
143 * the rejection reason is passed to the unhandled rejection handler.
144 * @private {boolean}
145 */
146 this.hadUnhandledRejection_ = false;
147 }
148
149 if (goog.Promise.LONG_STACK_TRACES) {
150 /**
151 * A list of stack trace frames pointing to the locations where this Promise
152 * was created or had callbacks added to it. Saved to add additional context
153 * to stack traces when an exception is thrown.
154 * @private {!Array<string>}
155 */
156 this.stack_ = [];
157 this.addStackTrace_(new Error('created'));
158
159 /**
160 * Index of the most recently executed stack frame entry.
161 * @private {number}
162 */
163 this.currentStep_ = 0;
164 }
165
166 // As an optimization, we can skip this if resolver is goog.nullFunction.
167 // This value is passed internally when creating a promise which will be
168 // resolved through a more optimized path.
169 if (resolver != goog.nullFunction) {
170 try {
171 var self = this;
172 resolver.call(
173 opt_context,
174 function(value) {
175 self.resolve_(goog.Promise.State_.FULFILLED, value);
176 },
177 function(reason) {
178 if (goog.DEBUG &&
179 !(reason instanceof goog.Promise.CancellationError)) {
180 try {
181 // Promise was rejected. Step up one call frame to see why.
182 if (reason instanceof Error) {
183 throw reason;
184 } else {
185 throw new Error('Promise rejected.');
186 }
187 } catch (e) {
188 // Only thrown so browser dev tools can catch rejections of
189 // promises when the option to break on caught exceptions is
190 // activated.
191 }
192 }
193 self.resolve_(goog.Promise.State_.REJECTED, reason);
194 });
195 } catch (e) {
196 this.resolve_(goog.Promise.State_.REJECTED, e);
197 }
198 }
199 };
200
201
202 /**
203 * @define {boolean} Whether traces of {@code then} calls should be included in
204 * exceptions thrown
205 */
206 goog.define('goog.Promise.LONG_STACK_TRACES', false);
207
208
209 /**
210 * @define {number} The delay in milliseconds before a rejected Promise's reason
211 * is passed to the rejection handler. By default, the rejection handler
212 * rethrows the rejection reason so that it appears in the developer console or
213 * {@code window.onerror} handler.
214 *
215 * Rejections are rethrown as quickly as possible by default. A negative value
216 * disables rejection handling entirely.
217 */
218 goog.define('goog.Promise.UNHANDLED_REJECTION_DELAY', 0);
219
220
221 /**
222 * The possible internal states for a Promise. These states are not directly
223 * observable to external callers.
224 * @enum {number}
225 * @private
226 */
227 goog.Promise.State_ = {
228 /** The Promise is waiting for resolution. */
229 PENDING: 0,
230
231 /** The Promise is blocked waiting for the result of another Thenable. */
232 BLOCKED: 1,
233
234 /** The Promise has been resolved with a fulfillment value. */
235 FULFILLED: 2,
236
237 /** The Promise has been resolved with a rejection reason. */
238 REJECTED: 3
239 };
240
241
242
243 /**
244 * Entries in the callback chain. Each call to {@code then},
245 * {@code thenCatch}, or {@code thenAlways} creates an entry containing the
246 * functions that may be invoked once the Promise is settled.
247 *
248 * @private @final @struct @constructor
249 */
250 goog.Promise.CallbackEntry_ = function() {
251 /** @type {?goog.Promise} */
252 this.child = null;
253 /** @type {Function} */
254 this.onFulfilled = null;
255 /** @type {Function} */
256 this.onRejected = null;
257 /** @type {?} */
258 this.context = null;
259 /** @type {?goog.Promise.CallbackEntry_} */
260 this.next = null;
261
262 /**
263 * A boolean value to indicate this is a "thenAlways" callback entry.
264 * Unlike a normal "then/thenVoid" a "thenAlways doesn't participate
265 * in "cancel" considerations but is simply an observer and requires
266 * special handling.
267 * @type {boolean}
268 */
269 this.always = false;
270 };
271
272
273 /** clear the object prior to reuse */
274 goog.Promise.CallbackEntry_.prototype.reset = function() {
275 this.child = null;
276 this.onFulfilled = null;
277 this.onRejected = null;
278 this.context = null;
279 this.always = false;
280 };
281
282
283 /**
284 * @define {number} The number of currently unused objects to keep around for
285 * reuse.
286 */
287 goog.define('goog.Promise.DEFAULT_MAX_UNUSED', 100);
288
289
290 /** @const @private {goog.async.FreeList<!goog.Promise.CallbackEntry_>} */
291 goog.Promise.freelist_ = new goog.async.FreeList(
292 function() { return new goog.Promise.CallbackEntry_(); },
293 function(item) { item.reset(); }, goog.Promise.DEFAULT_MAX_UNUSED);
294
295
296 /**
297 * @param {Function} onFulfilled
298 * @param {Function} onRejected
299 * @param {?} context
300 * @return {!goog.Promise.CallbackEntry_}
301 * @private
302 */
303 goog.Promise.getCallbackEntry_ = function(onFulfilled, onRejected, context) {
304 var entry = goog.Promise.freelist_.get();
305 entry.onFulfilled = onFulfilled;
306 entry.onRejected = onRejected;
307 entry.context = context;
308 return entry;
309 };
310
311
312 /**
313 * @param {!goog.Promise.CallbackEntry_} entry
314 * @private
315 */
316 goog.Promise.returnEntry_ = function(entry) {
317 goog.Promise.freelist_.put(entry);
318 };
319
320
321 // NOTE: this is the same template expression as is used for
322 // goog.IThenable.prototype.then
323
324
325 /**
326 * @param {VALUE=} opt_value
327 * @return {RESULT} A new Promise that is immediately resolved
328 * with the given value. If the input value is already a goog.Promise, it
329 * will be returned immediately without creating a new instance.
330 * @template VALUE
331 * @template RESULT := type('goog.Promise',
332 * cond(isUnknown(VALUE), unknown(),
333 * mapunion(VALUE, (V) =>
334 * cond(isTemplatized(V) && sub(rawTypeOf(V), 'IThenable'),
335 * templateTypeOf(V, 0),
336 * cond(sub(V, 'Thenable'),
337 * unknown(),
338 * V)))))
339 * =:
340 */
341 goog.Promise.resolve = function(opt_value) {
342 if (opt_value instanceof goog.Promise) {
343 // Avoid creating a new object if we already have a promise object
344 // of the correct type.
345 return opt_value;
346 }
347
348 // Passing goog.nullFunction will cause the constructor to take an optimized
349 // path that skips calling the resolver function.
350 var promise = new goog.Promise(goog.nullFunction);
351 promise.resolve_(goog.Promise.State_.FULFILLED, opt_value);
352 return promise;
353 };
354
355
356 /**
357 * @param {*=} opt_reason
358 * @return {!goog.Promise} A new Promise that is immediately rejected with the
359 * given reason.
360 */
361 goog.Promise.reject = function(opt_reason) {
362 return new goog.Promise(function(resolve, reject) { reject(opt_reason); });
363 };
364
365
366 /**
367 * This is identical to
368 * {@code goog.Promise.resolve(value).then(onFulfilled, onRejected)}, but it
369 * avoids creating an unnecessary wrapper Promise when {@code value} is already
370 * thenable.
371 *
372 * @param {?(goog.Thenable<TYPE>|Thenable|TYPE)} value
373 * @param {function(TYPE): ?} onFulfilled
374 * @param {function(*): *} onRejected
375 * @template TYPE
376 * @private
377 */
378 goog.Promise.resolveThen_ = function(value, onFulfilled, onRejected) {
379 var isThenable =
380 goog.Promise.maybeThen_(value, onFulfilled, onRejected, null);
381 if (!isThenable) {
382 goog.async.run(goog.partial(onFulfilled, value));
383 }
384 };
385
386
387 /**
388 * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}
389 * promises
390 * @return {!goog.Promise<TYPE>} A Promise that receives the result of the
391 * first Promise (or Promise-like) input to settle immediately after it
392 * settles.
393 * @template TYPE
394 */
395 goog.Promise.race = function(promises) {
396 return new goog.Promise(function(resolve, reject) {
397 if (!promises.length) {
398 resolve(undefined);
399 }
400 for (var i = 0, promise; i < promises.length; i++) {
401 promise = promises[i];
402 goog.Promise.resolveThen_(promise, resolve, reject);
403 }
404 });
405 };
406
407
408 /**
409 * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}
410 * promises
411 * @return {!goog.Promise<!Array<TYPE>>} A Promise that receives a list of
412 * every fulfilled value once every input Promise (or Promise-like) is
413 * successfully fulfilled, or is rejected with the first rejection reason
414 * immediately after it is rejected.
415 * @template TYPE
416 */
417 goog.Promise.all = function(promises) {
418 return new goog.Promise(function(resolve, reject) {
419 var toFulfill = promises.length;
420 var values = [];
421
422 if (!toFulfill) {
423 resolve(values);
424 return;
425 }
426
427 var onFulfill = function(index, value) {
428 toFulfill--;
429 values[index] = value;
430 if (toFulfill == 0) {
431 resolve(values);
432 }
433 };
434
435 var onReject = function(reason) { reject(reason); };
436
437 for (var i = 0, promise; i < promises.length; i++) {
438 promise = promises[i];
439 goog.Promise.resolveThen_(promise, goog.partial(onFulfill, i), onReject);
440 }
441 });
442 };
443
444
445 /**
446 * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}
447 * promises
448 * @return {!goog.Promise<!Array<{
449 * fulfilled: boolean,
450 * value: (TYPE|undefined),
451 * reason: (*|undefined)}>>} A Promise that resolves with a list of
452 * result objects once all input Promises (or Promise-like) have
453 * settled. Each result object contains a 'fulfilled' boolean indicating
454 * whether an input Promise was fulfilled or rejected. For fulfilled
455 * Promises, the resulting value is stored in the 'value' field. For
456 * rejected Promises, the rejection reason is stored in the 'reason'
457 * field.
458 * @template TYPE
459 */
460 goog.Promise.allSettled = function(promises) {
461 return new goog.Promise(function(resolve, reject) {
462 var toSettle = promises.length;
463 var results = [];
464
465 if (!toSettle) {
466 resolve(results);
467 return;
468 }
469
470 var onSettled = function(index, fulfilled, result) {
471 toSettle--;
472 results[index] = fulfilled ? {fulfilled: true, value: result} :
473 {fulfilled: false, reason: result};
474 if (toSettle == 0) {
475 resolve(results);
476 }
477 };
478
479 for (var i = 0, promise; i < promises.length; i++) {
480 promise = promises[i];
481 goog.Promise.resolveThen_(
482 promise, goog.partial(onSettled, i, true /* fulfilled */),
483 goog.partial(onSettled, i, false /* fulfilled */));
484 }
485 });
486 };
487
488
489 /**
490 * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}
491 * promises
492 * @return {!goog.Promise<TYPE>} A Promise that receives the value of the first
493 * input to be fulfilled, or is rejected with a list of every rejection
494 * reason if all inputs are rejected.
495 * @template TYPE
496 */
497 goog.Promise.firstFulfilled = function(promises) {
498 return new goog.Promise(function(resolve, reject) {
499 var toReject = promises.length;
500 var reasons = [];
501
502 if (!toReject) {
503 resolve(undefined);
504 return;
505 }
506
507 var onFulfill = function(value) { resolve(value); };
508
509 var onReject = function(index, reason) {
510 toReject--;
511 reasons[index] = reason;
512 if (toReject == 0) {
513 reject(reasons);
514 }
515 };
516
517 for (var i = 0, promise; i < promises.length; i++) {
518 promise = promises[i];
519 goog.Promise.resolveThen_(promise, onFulfill, goog.partial(onReject, i));
520 }
521 });
522 };
523
524
525 /**
526 * @return {!goog.promise.Resolver<TYPE>} Resolver wrapping the promise and its
527 * resolve / reject functions. Resolving or rejecting the resolver
528 * resolves or rejects the promise.
529 * @template TYPE
530 */
531 goog.Promise.withResolver = function() {
532 var resolve, reject;
533 var promise = new goog.Promise(function(rs, rj) {
534 resolve = rs;
535 reject = rj;
536 });
537 return new goog.Promise.Resolver_(promise, resolve, reject);
538 };
539
540
541 /**
542 * Adds callbacks that will operate on the result of the Promise, returning a
543 * new child Promise.
544 *
545 * If the Promise is fulfilled, the {@code onFulfilled} callback will be invoked
546 * with the fulfillment value as argument, and the child Promise will be
547 * fulfilled with the return value of the callback. If the callback throws an
548 * exception, the child Promise will be rejected with the thrown value instead.
549 *
550 * If the Promise is rejected, the {@code onRejected} callback will be invoked
551 * with the rejection reason as argument, and the child Promise will be resolved
552 * with the return value or rejected with the thrown value of the callback.
553 *
554 * @override
555 */
556 goog.Promise.prototype.then = function(
557 opt_onFulfilled, opt_onRejected, opt_context) {
558
559 if (opt_onFulfilled != null) {
560 goog.asserts.assertFunction(
561 opt_onFulfilled, 'opt_onFulfilled should be a function.');
562 }
563 if (opt_onRejected != null) {
564 goog.asserts.assertFunction(
565 opt_onRejected,
566 'opt_onRejected should be a function. Did you pass opt_context ' +
567 'as the second argument instead of the third?');
568 }
569
570 if (goog.Promise.LONG_STACK_TRACES) {
571 this.addStackTrace_(new Error('then'));
572 }
573
574 return this.addChildPromise_(
575 goog.isFunction(opt_onFulfilled) ? opt_onFulfilled : null,
576 goog.isFunction(opt_onRejected) ? opt_onRejected : null, opt_context);
577 };
578 goog.Thenable.addImplementation(goog.Promise);
579
580
581 /**
582 * Adds callbacks that will operate on the result of the Promise without
583 * returning a child Promise (unlike "then").
584 *
585 * If the Promise is fulfilled, the {@code onFulfilled} callback will be invoked
586 * with the fulfillment value as argument.
587 *
588 * If the Promise is rejected, the {@code onRejected} callback will be invoked
589 * with the rejection reason as argument.
590 *
591 * @param {?(function(this:THIS, TYPE):?)=} opt_onFulfilled A
592 * function that will be invoked with the fulfillment value if the Promise
593 * is fulfilled.
594 * @param {?(function(this:THIS, *): *)=} opt_onRejected A function that will
595 * be invoked with the rejection reason if the Promise is rejected.
596 * @param {THIS=} opt_context An optional context object that will be the
597 * execution context for the callbacks. By default, functions are executed
598 * with the default this.
599 * @package
600 * @template THIS
601 */
602 goog.Promise.prototype.thenVoid = function(
603 opt_onFulfilled, opt_onRejected, opt_context) {
604
605 if (opt_onFulfilled != null) {
606 goog.asserts.assertFunction(
607 opt_onFulfilled, 'opt_onFulfilled should be a function.');
608 }
609 if (opt_onRejected != null) {
610 goog.asserts.assertFunction(
611 opt_onRejected,
612 'opt_onRejected should be a function. Did you pass opt_context ' +
613 'as the second argument instead of the third?');
614 }
615
616 if (goog.Promise.LONG_STACK_TRACES) {
617 this.addStackTrace_(new Error('then'));
618 }
619
620 // Note: no default rejection handler is provided here as we need to
621 // distinguish unhandled rejections.
622 this.addCallbackEntry_(
623 goog.Promise.getCallbackEntry_(
624 opt_onFulfilled || goog.nullFunction, opt_onRejected || null,
625 opt_context));
626 };
627
628
629 /**
630 * Adds a callback that will be invoked when the Promise is settled (fulfilled
631 * or rejected). The callback receives no argument, and no new child Promise is
632 * created. This is useful for ensuring that cleanup takes place after certain
633 * asynchronous operations. Callbacks added with {@code thenAlways} will be
634 * executed in the same order with other calls to {@code then},
635 * {@code thenAlways}, or {@code thenCatch}.
636 *
637 * Since it does not produce a new child Promise, cancellation propagation is
638 * not prevented by adding callbacks with {@code thenAlways}. A Promise that has
639 * a cleanup handler added with {@code thenAlways} will be canceled if all of
640 * its children created by {@code then} (or {@code thenCatch}) are canceled.
641 * Additionally, since any rejections are not passed to the callback, it does
642 * not stop the unhandled rejection handler from running.
643 *
644 * @param {function(this:THIS): void} onSettled A function that will be invoked
645 * when the Promise is settled (fulfilled or rejected).
646 * @param {THIS=} opt_context An optional context object that will be the
647 * execution context for the callbacks. By default, functions are executed
648 * in the global scope.
649 * @return {!goog.Promise<TYPE>} This Promise, for chaining additional calls.
650 * @template THIS
651 */
652 goog.Promise.prototype.thenAlways = function(onSettled, opt_context) {
653 if (goog.Promise.LONG_STACK_TRACES) {
654 this.addStackTrace_(new Error('thenAlways'));
655 }
656
657 var entry = goog.Promise.getCallbackEntry_(onSettled, onSettled, opt_context);
658 entry.always = true;
659 this.addCallbackEntry_(entry);
660 return this;
661 };
662
663
664 /**
665 * Adds a callback that will be invoked only if the Promise is rejected. This
666 * is equivalent to {@code then(null, onRejected)}.
667 *
668 * @param {function(this:THIS, *): *} onRejected A function that will be
669 * invoked with the rejection reason if the Promise is rejected.
670 * @param {THIS=} opt_context An optional context object that will be the
671 * execution context for the callbacks. By default, functions are executed
672 * in the global scope.
673 * @return {!goog.Promise} A new Promise that will receive the result of the
674 * callback.
675 * @template THIS
676 */
677 goog.Promise.prototype.thenCatch = function(onRejected, opt_context) {
678 if (goog.Promise.LONG_STACK_TRACES) {
679 this.addStackTrace_(new Error('thenCatch'));
680 }
681 return this.addChildPromise_(null, onRejected, opt_context);
682 };
683
684
685 /**
686 * Cancels the Promise if it is still pending by rejecting it with a cancel
687 * Error. No action is performed if the Promise is already resolved.
688 *
689 * All child Promises of the canceled Promise will be rejected with the same
690 * cancel error, as with normal Promise rejection. If the Promise to be canceled
691 * is the only child of a pending Promise, the parent Promise will also be
692 * canceled. Cancellation may propagate upward through multiple generations.
693 *
694 * @param {string=} opt_message An optional debugging message for describing the
695 * cancellation reason.
696 */
697 goog.Promise.prototype.cancel = function(opt_message) {
698 if (this.state_ == goog.Promise.State_.PENDING) {
699 goog.async.run(function() {
700 var err = new goog.Promise.CancellationError(opt_message);
701 this.cancelInternal_(err);
702 }, this);
703 }
704 };
705
706
707 /**
708 * Cancels this Promise with the given error.
709 *
710 * @param {!Error} err The cancellation error.
711 * @private
712 */
713 goog.Promise.prototype.cancelInternal_ = function(err) {
714 if (this.state_ == goog.Promise.State_.PENDING) {
715 if (this.parent_) {
716 // Cancel the Promise and remove it from the parent's child list.
717 this.parent_.cancelChild_(this, err);
718 this.parent_ = null;
719 } else {
720 this.resolve_(goog.Promise.State_.REJECTED, err);
721 }
722 }
723 };
724
725
726 /**
727 * Cancels a child Promise from the list of callback entries. If the Promise has
728 * not already been resolved, reject it with a cancel error. If there are no
729 * other children in the list of callback entries, propagate the cancellation
730 * by canceling this Promise as well.
731 *
732 * @param {!goog.Promise} childPromise The Promise to cancel.
733 * @param {!Error} err The cancel error to use for rejecting the Promise.
734 * @private
735 */
736 goog.Promise.prototype.cancelChild_ = function(childPromise, err) {
737 if (!this.callbackEntries_) {
738 return;
739 }
740 var childCount = 0;
741 var childEntry = null;
742 var beforeChildEntry = null;
743
744 // Find the callback entry for the childPromise, and count whether there are
745 // additional child Promises.
746 for (var entry = this.callbackEntries_; entry; entry = entry.next) {
747 if (!entry.always) {
748 childCount++;
749 if (entry.child == childPromise) {
750 childEntry = entry;
751 }
752 if (childEntry && childCount > 1) {
753 break;
754 }
755 }
756 if (!childEntry) {
757 beforeChildEntry = entry;
758 }
759 }
760
761 // Can a child entry be missing?
762
763 // If the child Promise was the only child, cancel this Promise as well.
764 // Otherwise, reject only the child Promise with the cancel error.
765 if (childEntry) {
766 if (this.state_ == goog.Promise.State_.PENDING && childCount == 1) {
767 this.cancelInternal_(err);
768 } else {
769 if (beforeChildEntry) {
770 this.removeEntryAfter_(beforeChildEntry);
771 } else {
772 this.popEntry_();
773 }
774
775 this.executeCallback_(childEntry, goog.Promise.State_.REJECTED, err);
776 }
777 }
778 };
779
780
781 /**
782 * Adds a callback entry to the current Promise, and schedules callback
783 * execution if the Promise has already been settled.
784 *
785 * @param {goog.Promise.CallbackEntry_} callbackEntry Record containing
786 * {@code onFulfilled} and {@code onRejected} callbacks to execute after
787 * the Promise is settled.
788 * @private
789 */
790 goog.Promise.prototype.addCallbackEntry_ = function(callbackEntry) {
791 if (!this.hasEntry_() && (this.state_ == goog.Promise.State_.FULFILLED ||
792 this.state_ == goog.Promise.State_.REJECTED)) {
793 this.scheduleCallbacks_();
794 }
795 this.queueEntry_(callbackEntry);
796 };
797
798
799 /**
800 * Creates a child Promise and adds it to the callback entry list. The result of
801 * the child Promise is determined by the state of the parent Promise and the
802 * result of the {@code onFulfilled} or {@code onRejected} callbacks as
803 * specified in the Promise resolution procedure.
804 *
805 * @see http://promisesaplus.com/#the__method
806 *
807 * @param {?function(this:THIS, TYPE):
808 * (RESULT|goog.Promise<RESULT>|Thenable)} onFulfilled A callback that
809 * will be invoked if the Promise is fulfilled, or null.
810 * @param {?function(this:THIS, *): *} onRejected A callback that will be
811 * invoked if the Promise is rejected, or null.
812 * @param {THIS=} opt_context An optional execution context for the callbacks.
813 * in the default calling context.
814 * @return {!goog.Promise} The child Promise.
815 * @template RESULT,THIS
816 * @private
817 */
818 goog.Promise.prototype.addChildPromise_ = function(
819 onFulfilled, onRejected, opt_context) {
820
821 /** @type {goog.Promise.CallbackEntry_} */
822 var callbackEntry = goog.Promise.getCallbackEntry_(null, null, null);
823
824 callbackEntry.child = new goog.Promise(function(resolve, reject) {
825 // Invoke onFulfilled, or resolve with the parent's value if absent.
826 callbackEntry.onFulfilled = onFulfilled ? function(value) {
827 try {
828 var result = onFulfilled.call(opt_context, value);
829 resolve(result);
830 } catch (err) {
831 reject(err);
832 }
833 } : resolve;
834
835 // Invoke onRejected, or reject with the parent's reason if absent.
836 callbackEntry.onRejected = onRejected ? function(reason) {
837 try {
838 var result = onRejected.call(opt_context, reason);
839 if (!goog.isDef(result) &&
840 reason instanceof goog.Promise.CancellationError) {
841 // Propagate cancellation to children if no other result is returned.
842 reject(reason);
843 } else {
844 resolve(result);
845 }
846 } catch (err) {
847 reject(err);
848 }
849 } : reject;
850 });
851
852 callbackEntry.child.parent_ = this;
853 this.addCallbackEntry_(callbackEntry);
854 return callbackEntry.child;
855 };
856
857
858 /**
859 * Unblocks the Promise and fulfills it with the given value.
860 *
861 * @param {TYPE} value
862 * @private
863 */
864 goog.Promise.prototype.unblockAndFulfill_ = function(value) {
865 goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);
866 this.state_ = goog.Promise.State_.PENDING;
867 this.resolve_(goog.Promise.State_.FULFILLED, value);
868 };
869
870
871 /**
872 * Unblocks the Promise and rejects it with the given rejection reason.
873 *
874 * @param {*} reason
875 * @private
876 */
877 goog.Promise.prototype.unblockAndReject_ = function(reason) {
878 goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);
879 this.state_ = goog.Promise.State_.PENDING;
880 this.resolve_(goog.Promise.State_.REJECTED, reason);
881 };
882
883
884 /**
885 * Attempts to resolve a Promise with a given resolution state and value. This
886 * is a no-op if the given Promise has already been resolved.
887 *
888 * If the given result is a Thenable (such as another Promise), the Promise will
889 * be settled with the same state and result as the Thenable once it is itself
890 * settled.
891 *
892 * If the given result is not a Thenable, the Promise will be settled (fulfilled
893 * or rejected) with that result based on the given state.
894 *
895 * @see http://promisesaplus.com/#the_promise_resolution_procedure
896 *
897 * @param {goog.Promise.State_} state
898 * @param {*} x The result to apply to the Promise.
899 * @private
900 */
901 goog.Promise.prototype.resolve_ = function(state, x) {
902 if (this.state_ != goog.Promise.State_.PENDING) {
903 return;
904 }
905
906 if (this === x) {
907 state = goog.Promise.State_.REJECTED;
908 x = new TypeError('Promise cannot resolve to itself');
909 }
910
911 this.state_ = goog.Promise.State_.BLOCKED;
912 var isThenable = goog.Promise.maybeThen_(
913 x, this.unblockAndFulfill_, this.unblockAndReject_, this);
914 if (isThenable) {
915 return;
916 }
917
918 this.result_ = x;
919 this.state_ = state;
920 // Since we can no longer be canceled, remove link to parent, so that the
921 // child promise does not keep the parent promise alive.
922 this.parent_ = null;
923 this.scheduleCallbacks_();
924
925 if (state == goog.Promise.State_.REJECTED &&
926 !(x instanceof goog.Promise.CancellationError)) {
927 goog.Promise.addUnhandledRejection_(this, x);
928 }
929 };
930
931
932 /**
933 * Invokes the "then" method of an input value if that value is a Thenable. This
934 * is a no-op if the value is not thenable.
935 *
936 * @param {?} value A potentially thenable value.
937 * @param {!Function} onFulfilled
938 * @param {!Function} onRejected
939 * @param {?} context
940 * @return {boolean} Whether the input value was thenable.
941 * @private
942 */
943 goog.Promise.maybeThen_ = function(value, onFulfilled, onRejected, context) {
944 if (value instanceof goog.Promise) {
945 value.thenVoid(onFulfilled, onRejected, context);
946 return true;
947 } else if (goog.Thenable.isImplementedBy(value)) {
948 value = /** @type {!goog.Thenable} */ (value);
949 value.then(onFulfilled, onRejected, context);
950 return true;
951 } else if (goog.isObject(value)) {
952 try {
953 var then = value['then'];
954 if (goog.isFunction(then)) {
955 goog.Promise.tryThen_(value, then, onFulfilled, onRejected, context);
956 return true;
957 }
958 } catch (e) {
959 onRejected.call(context, e);
960 return true;
961 }
962 }
963
964 return false;
965 };
966
967
968 /**
969 * Attempts to call the {@code then} method on an object in the hopes that it is
970 * a Promise-compatible instance. This allows interoperation between different
971 * Promise implementations, however a non-compliant object may cause a Promise
972 * to hang indefinitely. If the {@code then} method throws an exception, the
973 * dependent Promise will be rejected with the thrown value.
974 *
975 * @see http://promisesaplus.com/#point-70
976 *
977 * @param {Thenable} thenable An object with a {@code then} method that may be
978 * compatible with the Promise/A+ specification.
979 * @param {!Function} then The {@code then} method of the Thenable object.
980 * @param {!Function} onFulfilled
981 * @param {!Function} onRejected
982 * @param {*} context
983 * @private
984 */
985 goog.Promise.tryThen_ = function(
986 thenable, then, onFulfilled, onRejected, context) {
987
988 var called = false;
989 var resolve = function(value) {
990 if (!called) {
991 called = true;
992 onFulfilled.call(context, value);
993 }
994 };
995
996 var reject = function(reason) {
997 if (!called) {
998 called = true;
999 onRejected.call(context, reason);
1000 }
1001 };
1002
1003 try {
1004 then.call(thenable, resolve, reject);
1005 } catch (e) {
1006 reject(e);
1007 }
1008 };
1009
1010
1011 /**
1012 * Executes the pending callbacks of a settled Promise after a timeout.
1013 *
1014 * Section 2.2.4 of the Promises/A+ specification requires that Promise
1015 * callbacks must only be invoked from a call stack that only contains Promise
1016 * implementation code, which we accomplish by invoking callback execution after
1017 * a timeout. If {@code startExecution_} is called multiple times for the same
1018 * Promise, the callback chain will be evaluated only once. Additional callbacks
1019 * may be added during the evaluation phase, and will be executed in the same
1020 * event loop.
1021 *
1022 * All Promises added to the waiting list during the same browser event loop
1023 * will be executed in one batch to avoid using a separate timeout per Promise.
1024 *
1025 * @private
1026 */
1027 goog.Promise.prototype.scheduleCallbacks_ = function() {
1028 if (!this.executing_) {
1029 this.executing_ = true;
1030 goog.async.run(this.executeCallbacks_, this);
1031 }
1032 };
1033
1034
1035 /**
1036 * @return {boolean} Whether there are any pending callbacks queued.
1037 * @private
1038 */
1039 goog.Promise.prototype.hasEntry_ = function() {
1040 return !!this.callbackEntries_;
1041 };
1042
1043
1044 /**
1045 * @param {goog.Promise.CallbackEntry_} entry
1046 * @private
1047 */
1048 goog.Promise.prototype.queueEntry_ = function(entry) {
1049 goog.asserts.assert(entry.onFulfilled != null);
1050
1051 if (this.callbackEntriesTail_) {
1052 this.callbackEntriesTail_.next = entry;
1053 this.callbackEntriesTail_ = entry;
1054 } else {
1055 // It the work queue was empty set the head too.
1056 this.callbackEntries_ = entry;
1057 this.callbackEntriesTail_ = entry;
1058 }
1059 };
1060
1061
1062 /**
1063 * @return {goog.Promise.CallbackEntry_} entry
1064 * @private
1065 */
1066 goog.Promise.prototype.popEntry_ = function() {
1067 var entry = null;
1068 if (this.callbackEntries_) {
1069 entry = this.callbackEntries_;
1070 this.callbackEntries_ = entry.next;
1071 entry.next = null;
1072 }
1073 // It the work queue is empty clear the tail too.
1074 if (!this.callbackEntries_) {
1075 this.callbackEntriesTail_ = null;
1076 }
1077
1078 if (entry != null) {
1079 goog.asserts.assert(entry.onFulfilled != null);
1080 }
1081 return entry;
1082 };
1083
1084
1085 /**
1086 * @param {goog.Promise.CallbackEntry_} previous
1087 * @private
1088 */
1089 goog.Promise.prototype.removeEntryAfter_ = function(previous) {
1090 goog.asserts.assert(this.callbackEntries_);
1091 goog.asserts.assert(previous != null);
1092 // If the last entry is being removed, update the tail
1093 if (previous.next == this.callbackEntriesTail_) {
1094 this.callbackEntriesTail_ = previous;
1095 }
1096
1097 previous.next = previous.next.next;
1098 };
1099
1100
1101 /**
1102 * Executes all pending callbacks for this Promise.
1103 *
1104 * @private
1105 */
1106 goog.Promise.prototype.executeCallbacks_ = function() {
1107 var entry = null;
1108 while (entry = this.popEntry_()) {
1109 if (goog.Promise.LONG_STACK_TRACES) {
1110 this.currentStep_++;
1111 }
1112 this.executeCallback_(entry, this.state_, this.result_);
1113 }
1114 this.executing_ = false;
1115 };
1116
1117
1118 /**
1119 * Executes a pending callback for this Promise. Invokes an {@code onFulfilled}
1120 * or {@code onRejected} callback based on the settled state of the Promise.
1121 *
1122 * @param {!goog.Promise.CallbackEntry_} callbackEntry An entry containing the
1123 * onFulfilled and/or onRejected callbacks for this step.
1124 * @param {goog.Promise.State_} state The resolution status of the Promise,
1125 * either FULFILLED or REJECTED.
1126 * @param {*} result The settled result of the Promise.
1127 * @private
1128 */
1129 goog.Promise.prototype.executeCallback_ = function(
1130 callbackEntry, state, result) {
1131 // Cancel an unhandled rejection if the then/thenVoid call had an onRejected.
1132 if (state == goog.Promise.State_.REJECTED && callbackEntry.onRejected &&
1133 !callbackEntry.always) {
1134 this.removeUnhandledRejection_();
1135 }
1136
1137 if (callbackEntry.child) {
1138 // When the parent is settled, the child no longer needs to hold on to it,
1139 // as the parent can no longer be canceled.
1140 callbackEntry.child.parent_ = null;
1141 goog.Promise.invokeCallback_(callbackEntry, state, result);
1142 } else {
1143 // Callbacks created with thenAlways or thenVoid do not have the rejection
1144 // handling code normally set up in the child Promise.
1145 try {
1146 callbackEntry.always ?
1147 callbackEntry.onFulfilled.call(callbackEntry.context) :
1148 goog.Promise.invokeCallback_(callbackEntry, state, result);
1149 } catch (err) {
1150 goog.Promise.handleRejection_.call(null, err);
1151 }
1152 }
1153 goog.Promise.returnEntry_(callbackEntry);
1154 };
1155
1156
1157 /**
1158 * Executes the onFulfilled or onRejected callback for a callbackEntry.
1159 *
1160 * @param {!goog.Promise.CallbackEntry_} callbackEntry
1161 * @param {goog.Promise.State_} state
1162 * @param {*} result
1163 * @private
1164 */
1165 goog.Promise.invokeCallback_ = function(callbackEntry, state, result) {
1166 if (state == goog.Promise.State_.FULFILLED) {
1167 callbackEntry.onFulfilled.call(callbackEntry.context, result);
1168 } else if (callbackEntry.onRejected) {
1169 callbackEntry.onRejected.call(callbackEntry.context, result);
1170 }
1171 };
1172
1173
1174 /**
1175 * Records a stack trace entry for functions that call {@code then} or the
1176 * Promise constructor. May be disabled by unsetting {@code LONG_STACK_TRACES}.
1177 *
1178 * @param {!Error} err An Error object created by the calling function for
1179 * providing a stack trace.
1180 * @private
1181 */
1182 goog.Promise.prototype.addStackTrace_ = function(err) {
1183 if (goog.Promise.LONG_STACK_TRACES && goog.isString(err.stack)) {
1184 // Extract the third line of the stack trace, which is the entry for the
1185 // user function that called into Promise code.
1186 var trace = err.stack.split('\n', 4)[3];
1187 var message = err.message;
1188
1189 // Pad the message to align the traces.
1190 message += Array(11 - message.length).join(' ');
1191 this.stack_.push(message + trace);
1192 }
1193 };
1194
1195
1196 /**
1197 * Adds extra stack trace information to an exception for the list of
1198 * asynchronous {@code then} calls that have been run for this Promise. Stack
1199 * trace information is recorded in {@see #addStackTrace_}, and appended to
1200 * rethrown errors when {@code LONG_STACK_TRACES} is enabled.
1201 *
1202 * @param {*} err An unhandled exception captured during callback execution.
1203 * @private
1204 */
1205 goog.Promise.prototype.appendLongStack_ = function(err) {
1206 if (goog.Promise.LONG_STACK_TRACES && err && goog.isString(err.stack) &&
1207 this.stack_.length) {
1208 var longTrace = ['Promise trace:'];
1209
1210 for (var promise = this; promise; promise = promise.parent_) {
1211 for (var i = this.currentStep_; i >= 0; i--) {
1212 longTrace.push(promise.stack_[i]);
1213 }
1214 longTrace.push(
1215 'Value: ' +
1216 '[' + (promise.state_ == goog.Promise.State_.REJECTED ? 'REJECTED' :
1217 'FULFILLED') +
1218 '] ' +
1219 '<' + String(promise.result_) + '>');
1220 }
1221 err.stack += '\n\n' + longTrace.join('\n');
1222 }
1223 };
1224
1225
1226 /**
1227 * Marks this rejected Promise as having being handled. Also marks any parent
1228 * Promises in the rejected state as handled. The rejection handler will no
1229 * longer be invoked for this Promise (if it has not been called already).
1230 *
1231 * @private
1232 */
1233 goog.Promise.prototype.removeUnhandledRejection_ = function() {
1234 if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {
1235 for (var p = this; p && p.unhandledRejectionId_; p = p.parent_) {
1236 goog.global.clearTimeout(p.unhandledRejectionId_);
1237 p.unhandledRejectionId_ = 0;
1238 }
1239 } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {
1240 for (var p = this; p && p.hadUnhandledRejection_; p = p.parent_) {
1241 p.hadUnhandledRejection_ = false;
1242 }
1243 }
1244 };
1245
1246
1247 /**
1248 * Marks this rejected Promise as unhandled. If no {@code onRejected} callback
1249 * is called for this Promise before the {@code UNHANDLED_REJECTION_DELAY}
1250 * expires, the reason will be passed to the unhandled rejection handler. The
1251 * handler typically rethrows the rejection reason so that it becomes visible in
1252 * the developer console.
1253 *
1254 * @param {!goog.Promise} promise The rejected Promise.
1255 * @param {*} reason The Promise rejection reason.
1256 * @private
1257 */
1258 goog.Promise.addUnhandledRejection_ = function(promise, reason) {
1259 if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {
1260 promise.unhandledRejectionId_ = goog.global.setTimeout(function() {
1261 promise.appendLongStack_(reason);
1262 goog.Promise.handleRejection_.call(null, reason);
1263 }, goog.Promise.UNHANDLED_REJECTION_DELAY);
1264
1265 } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {
1266 promise.hadUnhandledRejection_ = true;
1267 goog.async.run(function() {
1268 if (promise.hadUnhandledRejection_) {
1269 promise.appendLongStack_(reason);
1270 goog.Promise.handleRejection_.call(null, reason);
1271 }
1272 });
1273 }
1274 };
1275
1276
1277 /**
1278 * A method that is invoked with the rejection reasons for Promises that are
1279 * rejected but have no {@code onRejected} callbacks registered yet.
1280 * @type {function(*)}
1281 * @private
1282 */
1283 goog.Promise.handleRejection_ = goog.async.throwException;
1284
1285
1286 /**
1287 * Sets a handler that will be called with reasons from unhandled rejected
1288 * Promises. If the rejected Promise (or one of its descendants) has an
1289 * {@code onRejected} callback registered, the rejection will be considered
1290 * handled, and the rejection handler will not be called.
1291 *
1292 * By default, unhandled rejections are rethrown so that the error may be
1293 * captured by the developer console or a {@code window.onerror} handler.
1294 *
1295 * @param {function(*)} handler A function that will be called with reasons from
1296 * rejected Promises. Defaults to {@code goog.async.throwException}.
1297 */
1298 goog.Promise.setUnhandledRejectionHandler = function(handler) {
1299 goog.Promise.handleRejection_ = handler;
1300 };
1301
1302
1303
1304 /**
1305 * Error used as a rejection reason for canceled Promises.
1306 *
1307 * @param {string=} opt_message
1308 * @constructor
1309 * @extends {goog.debug.Error}
1310 * @final
1311 */
1312 goog.Promise.CancellationError = function(opt_message) {
1313 goog.Promise.CancellationError.base(this, 'constructor', opt_message);
1314 };
1315 goog.inherits(goog.Promise.CancellationError, goog.debug.Error);
1316
1317
1318 /** @override */
1319 goog.Promise.CancellationError.prototype.name = 'cancel';
1320
1321
1322
1323 /**
1324 * Internal implementation of the resolver interface.
1325 *
1326 * @param {!goog.Promise<TYPE>} promise
1327 * @param {function((TYPE|goog.Promise<TYPE>|Thenable)=)} resolve
1328 * @param {function(*=): void} reject
1329 * @implements {goog.promise.Resolver<TYPE>}
1330 * @final @struct
1331 * @constructor
1332 * @private
1333 * @template TYPE
1334 */
1335 goog.Promise.Resolver_ = function(promise, resolve, reject) {
1336 /** @const */
1337 this.promise = promise;
1338
1339 /** @const */
1340 this.resolve = resolve;
1341
1342 /** @const */
1343 this.reject = reject;
1344 };