# lib/goog/promise/promise.js

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.run');
20 | goog.require('goog.async.throwException');
21 | goog.require('goog.debug.Error');
22 | goog.require('goog.promise.Resolver');
23 |
24 |
25 |
26 | /**
27 | * Promises provide a result that may be resolved asynchronously. A Promise may
28 | * be resolved by being fulfilled or rejected with a value, which will be known
29 | * as the fulfillment value or the rejection reason. Whether fulfilled or
30 | * rejected, the Promise result is immutable once it is set.
31 | *
32 | * Promises may represent results of any type, including undefined. Rejection
33 | * reasons are typically Errors, but may also be of any type. Closure Promises
34 | * allow for optional type annotations that enforce that fulfillment values are
35 | * of the appropriate types at compile time.
36 | *
37 | * The result of a Promise is accessible by calling {@code then} and registering
38 | * {@code onFulfilled} and {@code onRejected} callbacks. Once the Promise
39 | * resolves, the relevant callbacks are invoked with the fulfillment value or
40 | * rejection reason as argument. Callbacks are always invoked in the order they
41 | * were registered, even when additional {@code then} calls are made from inside
42 | * another callback. A callback is always run asynchronously sometime after the
43 | * scope containing the registering {@code then} invocation has returned.
44 | *
45 | * If a Promise is resolved with another Promise, the first Promise will block
46 | * until the second is resolved, and then assumes the same result as the second
47 | * Promise. This allows Promises to depend on the results of other Promises,
48 | * linking together multiple asynchronous operations.
49 | *
50 | * This implementation is compatible with the Promises/A+ specification and
51 | * passes that specification's conformance test suite. A Closure Promise may be
52 | * resolved with a Promise instance (or sufficiently compatible Promise-like
53 | * object) created by other Promise implementations. From the specification,
54 | * Promise-like objects are known as "Thenables".
55 | *
56 | * @see http://promisesaplus.com/
57 | *
58 | * @param {function(
59 | * this:RESOLVER_CONTEXT,
60 | * function((TYPE|IThenable<TYPE>|Thenable)=),
61 | * function(*)): void} resolver
62 | * Initialization function that is invoked immediately with {@code resolve}
63 | * and {@code reject} functions as arguments. The Promise is resolved or
64 | * rejected with the first argument passed to either function.
65 | * @param {RESOLVER_CONTEXT=} opt_context An optional context for executing the
66 | * resolver function. If unspecified, the resolver function will be executed
67 | * in the default scope.
68 | * @constructor
69 | * @struct
70 | * @final
71 | * @implements {goog.Thenable<TYPE>}
72 | * @template TYPE,RESOLVER_CONTEXT
73 | */
74 | goog.Promise = function(resolver, opt_context) {
75 | /**
76 | * The internal state of this Promise. Either PENDING, FULFILLED, REJECTED, or
77 | * BLOCKED.
78 | * @private {goog.Promise.State_}
79 | */
80 | this.state_ = goog.Promise.State_.PENDING;
81 |
82 | /**
83 | * The resolved result of the Promise. Immutable once set with either a
84 | * fulfillment value or rejection reason.
85 | * @private {*}
86 | */
87 | this.result_ = undefined;
88 |
89 | /**
90 | * For Promises created by calling {@code then()}, the originating parent.
91 | * @private {goog.Promise}
92 | */
93 | this.parent_ = null;
94 |
95 | /**
96 | * The list of {@code onFulfilled} and {@code onRejected} callbacks added to
97 | * this Promise by calls to {@code then()}.
98 | * @private {Array<goog.Promise.CallbackEntry_>}
99 | */
100 | this.callbackEntries_ = null;
101 |
102 | /**
103 | * Whether the Promise is in the queue of Promises to execute.
104 | * @private {boolean}
105 | */
106 | this.executing_ = false;
107 |
108 | if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {
109 | /**
110 | * A timeout ID used when the {@code UNHANDLED_REJECTION_DELAY} is greater
111 | * than 0 milliseconds. The ID is set when the Promise is rejected, and
112 | * cleared only if an {@code onRejected} callback is invoked for the
113 | * Promise (or one of its descendants) before the delay is exceeded.
114 | *
115 | * If the rejection is not handled before the timeout completes, the
116 | * rejection reason is passed to the unhandled rejection handler.
117 | * @private {number}
118 | */
119 | this.unhandledRejectionId_ = 0;
120 | } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {
121 | /**
122 | * When the {@code UNHANDLED_REJECTION_DELAY} is set to 0 milliseconds, a
123 | * boolean that is set if the Promise is rejected, and reset to false if an
124 | * {@code onRejected} callback is invoked for the Promise (or one of its
125 | * descendants). If the rejection is not handled before the next timestep,
126 | * the rejection reason is passed to the unhandled rejection handler.
127 | * @private {boolean}
128 | */
129 | this.hadUnhandledRejection_ = false;
130 | }
131 |
132 | if (goog.Promise.LONG_STACK_TRACES) {
133 | /**
134 | * A list of stack trace frames pointing to the locations where this Promise
135 | * was created or had callbacks added to it. Saved to add additional context
136 | * to stack traces when an exception is thrown.
137 | * @private {!Array<string>}
138 | */
139 | this.stack_ = [];
140 | this.addStackTrace_(new Error('created'));
141 |
142 | /**
143 | * Index of the most recently executed stack frame entry.
144 | * @private {number}
145 | */
146 | this.currentStep_ = 0;
147 | }
148 |
149 | try {
150 | var self = this;
151 | resolver.call(
152 | opt_context,
153 | function(value) {
154 | self.resolve_(goog.Promise.State_.FULFILLED, value);
155 | },
156 | function(reason) {
157 | if (goog.DEBUG &&
158 | !(reason instanceof goog.Promise.CancellationError)) {
159 | try {
160 | // Promise was rejected. Step up one call frame to see why.
161 | if (reason instanceof Error) {
162 | throw reason;
163 | } else {
164 | throw new Error('Promise rejected.');
165 | }
166 | } catch (e) {
167 | // Only thrown so browser dev tools can catch rejections of
168 | // promises when the option to break on caught exceptions is
169 | // activated.
170 | }
171 | }
172 | self.resolve_(goog.Promise.State_.REJECTED, reason);
173 | });
174 | } catch (e) {
175 | this.resolve_(goog.Promise.State_.REJECTED, e);
176 | }
177 | };
178 |
179 |
180 | /**
181 | * @define {boolean} Whether traces of {@code then} calls should be included in
182 | * exceptions thrown
183 | */
184 | goog.define('goog.Promise.LONG_STACK_TRACES', false);
185 |
186 |
187 | /**
188 | * @define {number} The delay in milliseconds before a rejected Promise's reason
189 | * is passed to the rejection handler. By default, the rejection handler
190 | * rethrows the rejection reason so that it appears in the developer console or
191 | * {@code window.onerror} handler.
192 | *
193 | * Rejections are rethrown as quickly as possible by default. A negative value
194 | * disables rejection handling entirely.
195 | */
196 | goog.define('goog.Promise.UNHANDLED_REJECTION_DELAY', 0);
197 |
198 |
199 | /**
200 | * The possible internal states for a Promise. These states are not directly
201 | * observable to external callers.
202 | * @enum {number}
203 | * @private
204 | */
205 | goog.Promise.State_ = {
206 | /** The Promise is waiting for resolution. */
207 | PENDING: 0,
208 |
209 | /** The Promise is blocked waiting for the result of another Thenable. */
210 | BLOCKED: 1,
211 |
212 | /** The Promise has been resolved with a fulfillment value. */
213 | FULFILLED: 2,
214 |
215 | /** The Promise has been resolved with a rejection reason. */
216 | REJECTED: 3
217 | };
218 |
219 |
220 | /**
221 | * Typedef for entries in the callback chain. Each call to {@code then},
222 | * {@code thenCatch}, or {@code thenAlways} creates an entry containing the
223 | * functions that may be invoked once the Promise is resolved.
224 | *
225 | * @typedef {{
226 | * child: goog.Promise,
227 | * onFulfilled: function(*),
228 | * onRejected: function(*)
229 | * }}
230 | * @private
231 | */
232 | goog.Promise.CallbackEntry_;
233 |
234 |
235 | /**
236 | * @param {(TYPE|goog.Thenable<TYPE>|Thenable)=} opt_value
237 | * @return {!goog.Promise<TYPE>} A new Promise that is immediately resolved
238 | * with the given value.
239 | * @template TYPE
240 | */
241 | goog.Promise.resolve = function(opt_value) {
242 | return new goog.Promise(function(resolve, reject) {
243 | resolve(opt_value);
244 | });
245 | };
246 |
247 |
248 | /**
249 | * @param {*=} opt_reason
250 | * @return {!goog.Promise} A new Promise that is immediately rejected with the
251 | * given reason.
252 | */
253 | goog.Promise.reject = function(opt_reason) {
254 | return new goog.Promise(function(resolve, reject) {
255 | reject(opt_reason);
256 | });
257 | };
258 |
259 |
260 | /**
261 | * @param {!Array<!(goog.Thenable<TYPE>|Thenable)>} promises
262 | * @return {!goog.Promise<TYPE>} A Promise that receives the result of the
263 | * first Promise (or Promise-like) input to complete.
264 | * @template TYPE
265 | */
266 | goog.Promise.race = function(promises) {
267 | return new goog.Promise(function(resolve, reject) {
268 | if (!promises.length) {
269 | resolve(undefined);
270 | }
271 | for (var i = 0, promise; promise = promises[i]; i++) {
272 | promise.then(resolve, reject);
273 | }
274 | });
275 | };
276 |
277 |
278 | /**
279 | * @param {!Array<!(goog.Thenable<TYPE>|Thenable)>} promises
280 | * @return {!goog.Promise<!Array<TYPE>>} A Promise that receives a list of
281 | * every fulfilled value once every input Promise (or Promise-like) is
282 | * successfully fulfilled, or is rejected by the first rejection result.
283 | * @template TYPE
284 | */
285 | goog.Promise.all = function(promises) {
286 | return new goog.Promise(function(resolve, reject) {
287 | var toFulfill = promises.length;
288 | var values = [];
289 |
290 | if (!toFulfill) {
291 | resolve(values);
292 | return;
293 | }
294 |
295 | var onFulfill = function(index, value) {
296 | toFulfill--;
297 | values[index] = value;
298 | if (toFulfill == 0) {
299 | resolve(values);
300 | }
301 | };
302 |
303 | var onReject = function(reason) {
304 | reject(reason);
305 | };
306 |
307 | for (var i = 0, promise; promise = promises[i]; i++) {
308 | promise.then(goog.partial(onFulfill, i), onReject);
309 | }
310 | });
311 | };
312 |
313 |
314 | /**
315 | * @param {!Array<!(goog.Thenable<TYPE>|Thenable)>} promises
316 | * @return {!goog.Promise<TYPE>} A Promise that receives the value of the first
317 | * input to be fulfilled, or is rejected with a list of every rejection
318 | * reason if all inputs are rejected.
319 | * @template TYPE
320 | */
321 | goog.Promise.firstFulfilled = function(promises) {
322 | return new goog.Promise(function(resolve, reject) {
323 | var toReject = promises.length;
324 | var reasons = [];
325 |
326 | if (!toReject) {
327 | resolve(undefined);
328 | return;
329 | }
330 |
331 | var onFulfill = function(value) {
332 | resolve(value);
333 | };
334 |
335 | var onReject = function(index, reason) {
336 | toReject--;
337 | reasons[index] = reason;
338 | if (toReject == 0) {
339 | reject(reasons);
340 | }
341 | };
342 |
343 | for (var i = 0, promise; promise = promises[i]; i++) {
344 | promise.then(onFulfill, goog.partial(onReject, i));
345 | }
346 | });
347 | };
348 |
349 |
350 | /**
351 | * @return {!goog.promise.Resolver<TYPE>} Resolver wrapping the promise and its
352 | * resolve / reject functions. Resolving or rejecting the resolver
353 | * resolves or rejects the promise.
354 | * @template TYPE
355 | */
356 | goog.Promise.withResolver = function() {
357 | var resolve, reject;
358 | var promise = new goog.Promise(function(rs, rj) {
359 | resolve = rs;
360 | reject = rj;
361 | });
362 | return new goog.Promise.Resolver_(promise, resolve, reject);
363 | };
364 |
365 |
366 | /**
367 | * Adds callbacks that will operate on the result of the Promise, returning a
368 | * new child Promise.
369 | *
370 | * If the Promise is fulfilled, the {@code onFulfilled} callback will be invoked
371 | * with the fulfillment value as argument, and the child Promise will be
372 | * fulfilled with the return value of the callback. If the callback throws an
373 | * exception, the child Promise will be rejected with the thrown value instead.
374 | *
375 | * If the Promise is rejected, the {@code onRejected} callback will be invoked
376 | * with the rejection reason as argument, and the child Promise will be resolved
377 | * with the return value or rejected with the thrown value of the callback.
378 | *
379 | * @override
380 | */
381 | goog.Promise.prototype.then = function(
382 | opt_onFulfilled, opt_onRejected, opt_context) {
383 |
384 | if (opt_onFulfilled != null) {
385 | goog.asserts.assertFunction(opt_onFulfilled,
386 | 'opt_onFulfilled should be a function.');
387 | }
388 | if (opt_onRejected != null) {
389 | goog.asserts.assertFunction(opt_onRejected,
390 | 'opt_onRejected should be a function. Did you pass opt_context ' +
391 | 'as the second argument instead of the third?');
392 | }
393 |
394 | if (goog.Promise.LONG_STACK_TRACES) {
395 | this.addStackTrace_(new Error('then'));
396 | }
397 |
398 | return this.addChildPromise_(
399 | goog.isFunction(opt_onFulfilled) ? opt_onFulfilled : null,
400 | goog.isFunction(opt_onRejected) ? opt_onRejected : null,
401 | opt_context);
402 | };
403 | goog.Thenable.addImplementation(goog.Promise);
404 |
405 |
406 | /**
407 | * Adds a callback that will be invoked whether the Promise is fulfilled or
408 | * rejected. The callback receives no argument, and no new child Promise is
409 | * created. This is useful for ensuring that cleanup takes place after certain
410 | * asynchronous operations. Callbacks added with {@code thenAlways} will be
411 | * executed in the same order with other calls to {@code then},
412 | * {@code thenAlways}, or {@code thenCatch}.
413 | *
414 | * Since it does not produce a new child Promise, cancellation propagation is
415 | * not prevented by adding callbacks with {@code thenAlways}. A Promise that has
416 | * a cleanup handler added with {@code thenAlways} will be canceled if all of
417 | * its children created by {@code then} (or {@code thenCatch}) are canceled.
418 | * Additionally, since any rejections are not passed to the callback, it does
419 | * not stop the unhandled rejection handler from running.
420 | *
421 | * @param {function(this:THIS): void} onResolved A function that will be invoked
422 | * when the Promise is resolved.
423 | * @param {THIS=} opt_context An optional context object that will be the
424 | * execution context for the callbacks. By default, functions are executed
425 | * in the global scope.
426 | * @return {!goog.Promise<TYPE>} This Promise, for chaining additional calls.
427 | * @template THIS
428 | */
429 | goog.Promise.prototype.thenAlways = function(onResolved, opt_context) {
430 | if (goog.Promise.LONG_STACK_TRACES) {
431 | this.addStackTrace_(new Error('thenAlways'));
432 | }
433 |
434 | var callback = function() {
435 | try {
436 | // Ensure that no arguments are passed to onResolved.
437 | onResolved.call(opt_context);
438 | } catch (err) {
439 | goog.Promise.handleRejection_.call(null, err);
440 | }
441 | };
442 |
443 | this.addCallbackEntry_({
444 | child: null,
445 | onRejected: callback,
446 | onFulfilled: callback
447 | });
448 | return this;
449 | };
450 |
451 |
452 | /**
453 | * Adds a callback that will be invoked only if the Promise is rejected. This
454 | * is equivalent to {@code then(null, onRejected)}.
455 | *
456 | * @param {!function(this:THIS, *): *} onRejected A function that will be
457 | * invoked with the rejection reason if the Promise is rejected.
458 | * @param {THIS=} opt_context An optional context object that will be the
459 | * execution context for the callbacks. By default, functions are executed
460 | * in the global scope.
461 | * @return {!goog.Promise} A new Promise that will receive the result of the
462 | * callback.
463 | * @template THIS
464 | */
465 | goog.Promise.prototype.thenCatch = function(onRejected, opt_context) {
466 | if (goog.Promise.LONG_STACK_TRACES) {
467 | this.addStackTrace_(new Error('thenCatch'));
468 | }
469 | return this.addChildPromise_(null, onRejected, opt_context);
470 | };
471 |
472 |
473 | /**
474 | * Cancels the Promise if it is still pending by rejecting it with a cancel
475 | * Error. No action is performed if the Promise is already resolved.
476 | *
477 | * All child Promises of the canceled Promise will be rejected with the same
478 | * cancel error, as with normal Promise rejection. If the Promise to be canceled
479 | * is the only child of a pending Promise, the parent Promise will also be
480 | * canceled. Cancellation may propagate upward through multiple generations.
481 | *
482 | * @param {string=} opt_message An optional debugging message for describing the
483 | * cancellation reason.
484 | */
485 | goog.Promise.prototype.cancel = function(opt_message) {
486 | if (this.state_ == goog.Promise.State_.PENDING) {
487 | goog.async.run(function() {
488 | var err = new goog.Promise.CancellationError(opt_message);
489 | this.cancelInternal_(err);
490 | }, this);
491 | }
492 | };
493 |
494 |
495 | /**
496 | * Cancels this Promise with the given error.
497 | *
498 | * @param {!Error} err The cancellation error.
499 | * @private
500 | */
501 | goog.Promise.prototype.cancelInternal_ = function(err) {
502 | if (this.state_ == goog.Promise.State_.PENDING) {
503 | if (this.parent_) {
504 | // Cancel the Promise and remove it from the parent's child list.
505 | this.parent_.cancelChild_(this, err);
506 | } else {
507 | this.resolve_(goog.Promise.State_.REJECTED, err);
508 | }
509 | }
510 | };
511 |
512 |
513 | /**
514 | * Cancels a child Promise from the list of callback entries. If the Promise has
515 | * not already been resolved, reject it with a cancel error. If there are no
516 | * other children in the list of callback entries, propagate the cancellation
517 | * by canceling this Promise as well.
518 | *
519 | * @param {!goog.Promise} childPromise The Promise to cancel.
520 | * @param {!Error} err The cancel error to use for rejecting the Promise.
521 | * @private
522 | */
523 | goog.Promise.prototype.cancelChild_ = function(childPromise, err) {
524 | if (!this.callbackEntries_) {
525 | return;
526 | }
527 | var childCount = 0;
528 | var childIndex = -1;
529 |
530 | // Find the callback entry for the childPromise, and count whether there are
531 | // additional child Promises.
532 | for (var i = 0, entry; entry = this.callbackEntries_[i]; i++) {
533 | var child = entry.child;
534 | if (child) {
535 | childCount++;
536 | if (child == childPromise) {
537 | childIndex = i;
538 | }
539 | if (childIndex >= 0 && childCount > 1) {
540 | break;
541 | }
542 | }
543 | }
544 |
545 | // If the child Promise was the only child, cancel this Promise as well.
546 | // Otherwise, reject only the child Promise with the cancel error.
547 | if (childIndex >= 0) {
548 | if (this.state_ == goog.Promise.State_.PENDING && childCount == 1) {
549 | this.cancelInternal_(err);
550 | } else {
551 | var callbackEntry = this.callbackEntries_.splice(childIndex, 1)[0];
552 | this.executeCallback_(
553 | callbackEntry, goog.Promise.State_.REJECTED, err);
554 | }
555 | }
556 | };
557 |
558 |
559 | /**
560 | * Adds a callback entry to the current Promise, and schedules callback
561 | * execution if the Promise has already been resolved.
562 | *
563 | * @param {goog.Promise.CallbackEntry_} callbackEntry Record containing
564 | * {@code onFulfilled} and {@code onRejected} callbacks to execute after
565 | * the Promise is resolved.
566 | * @private
567 | */
568 | goog.Promise.prototype.addCallbackEntry_ = function(callbackEntry) {
569 | if ((!this.callbackEntries_ || !this.callbackEntries_.length) &&
570 | (this.state_ == goog.Promise.State_.FULFILLED ||
571 | this.state_ == goog.Promise.State_.REJECTED)) {
572 | this.scheduleCallbacks_();
573 | }
574 | if (!this.callbackEntries_) {
575 | this.callbackEntries_ = [];
576 | }
577 | this.callbackEntries_.push(callbackEntry);
578 | };
579 |
580 |
581 | /**
582 | * Creates a child Promise and adds it to the callback entry list. The result of
583 | * the child Promise is determined by the state of the parent Promise and the
584 | * result of the {@code onFulfilled} or {@code onRejected} callbacks as
585 | * specified in the Promise resolution procedure.
586 | *
587 | * @see http://promisesaplus.com/#the__method
588 | *
589 | * @param {?function(this:THIS, TYPE):
590 | * (RESULT|goog.Promise<RESULT>|Thenable)} onFulfilled A callback that
591 | * will be invoked if the Promise is fullfilled, or null.
592 | * @param {?function(this:THIS, *): *} onRejected A callback that will be
593 | * invoked if the Promise is rejected, or null.
594 | * @param {THIS=} opt_context An optional execution context for the callbacks.
595 | * in the default calling context.
596 | * @return {!goog.Promise} The child Promise.
597 | * @template RESULT,THIS
598 | * @private
599 | */
600 | goog.Promise.prototype.addChildPromise_ = function(
601 | onFulfilled, onRejected, opt_context) {
602 |
603 | var callbackEntry = {
604 | child: null,
605 | onFulfilled: null,
606 | onRejected: null
607 | };
608 |
609 | callbackEntry.child = new goog.Promise(function(resolve, reject) {
610 | // Invoke onFulfilled, or resolve with the parent's value if absent.
611 | callbackEntry.onFulfilled = onFulfilled ? function(value) {
612 | try {
613 | var result = onFulfilled.call(opt_context, value);
614 | resolve(result);
615 | } catch (err) {
616 | reject(err);
617 | }
618 | } : resolve;
619 |
620 | // Invoke onRejected, or reject with the parent's reason if absent.
621 | callbackEntry.onRejected = onRejected ? function(reason) {
622 | try {
623 | var result = onRejected.call(opt_context, reason);
624 | if (!goog.isDef(result) &&
625 | reason instanceof goog.Promise.CancellationError) {
626 | // Propagate cancellation to children if no other result is returned.
627 | reject(reason);
628 | } else {
629 | resolve(result);
630 | }
631 | } catch (err) {
632 | reject(err);
633 | }
634 | } : reject;
635 | });
636 |
637 | callbackEntry.child.parent_ = this;
638 | this.addCallbackEntry_(
639 | /** @type {goog.Promise.CallbackEntry_} */ (callbackEntry));
640 | return callbackEntry.child;
641 | };
642 |
643 |
644 | /**
645 | * Unblocks the Promise and fulfills it with the given value.
646 | *
647 | * @param {TYPE} value
648 | * @private
649 | */
650 | goog.Promise.prototype.unblockAndFulfill_ = function(value) {
651 | goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);
652 | this.state_ = goog.Promise.State_.PENDING;
653 | this.resolve_(goog.Promise.State_.FULFILLED, value);
654 | };
655 |
656 |
657 | /**
658 | * Unblocks the Promise and rejects it with the given rejection reason.
659 | *
660 | * @param {*} reason
661 | * @private
662 | */
663 | goog.Promise.prototype.unblockAndReject_ = function(reason) {
664 | goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);
665 | this.state_ = goog.Promise.State_.PENDING;
666 | this.resolve_(goog.Promise.State_.REJECTED, reason);
667 | };
668 |
669 |
670 | /**
671 | * Attempts to resolve a Promise with a given resolution state and value. This
672 | * is a no-op if the given Promise has already been resolved.
673 | *
674 | * If the given result is a Thenable (such as another Promise), the Promise will
675 | * be resolved with the same state and result as the Thenable once it is itself
676 | * resolved.
677 | *
678 | * If the given result is not a Thenable, the Promise will be fulfilled or
679 | * rejected with that result based on the given state.
680 | *
681 | * @see http://promisesaplus.com/#the_promise_resolution_procedure
682 | *
683 | * @param {goog.Promise.State_} state
684 | * @param {*} x The result to apply to the Promise.
685 | * @private
686 | */
687 | goog.Promise.prototype.resolve_ = function(state, x) {
688 | if (this.state_ != goog.Promise.State_.PENDING) {
689 | return;
690 | }
691 |
692 | if (this == x) {
693 | state = goog.Promise.State_.REJECTED;
694 | x = new TypeError('Promise cannot resolve to itself');
695 |
696 | } else if (goog.Thenable.isImplementedBy(x)) {
697 | x = /** @type {!goog.Thenable} */ (x);
698 | this.state_ = goog.Promise.State_.BLOCKED;
699 | x.then(this.unblockAndFulfill_, this.unblockAndReject_, this);
700 | return;
701 |
702 | } else if (goog.isObject(x)) {
703 | try {
704 | var then = x['then'];
705 | if (goog.isFunction(then)) {
706 | this.tryThen_(x, then);
707 | return;
708 | }
709 | } catch (e) {
710 | state = goog.Promise.State_.REJECTED;
711 | x = e;
712 | }
713 | }
714 |
715 | this.result_ = x;
716 | this.state_ = state;
717 | this.scheduleCallbacks_();
718 |
719 | if (state == goog.Promise.State_.REJECTED &&
720 | !(x instanceof goog.Promise.CancellationError)) {
721 | goog.Promise.addUnhandledRejection_(this, x);
722 | }
723 | };
724 |
725 |
726 | /**
727 | * Attempts to call the {@code then} method on an object in the hopes that it is
728 | * a Promise-compatible instance. This allows interoperation between different
729 | * Promise implementations, however a non-compliant object may cause a Promise
730 | * to hang indefinitely. If the {@code then} method throws an exception, the
731 | * dependent Promise will be rejected with the thrown value.
732 | *
733 | * @see http://promisesaplus.com/#point-70
734 | *
735 | * @param {Thenable} thenable An object with a {@code then} method that may be
736 | * compatible with the Promise/A+ specification.
737 | * @param {!Function} then The {@code then} method of the Thenable object.
738 | * @private
739 | */
740 | goog.Promise.prototype.tryThen_ = function(thenable, then) {
741 | this.state_ = goog.Promise.State_.BLOCKED;
742 | var promise = this;
743 | var called = false;
744 |
745 | var resolve = function(value) {
746 | if (!called) {
747 | called = true;
748 | promise.unblockAndFulfill_(value);
749 | }
750 | };
751 |
752 | var reject = function(reason) {
753 | if (!called) {
754 | called = true;
755 | promise.unblockAndReject_(reason);
756 | }
757 | };
758 |
759 | try {
760 | then.call(thenable, resolve, reject);
761 | } catch (e) {
762 | reject(e);
763 | }
764 | };
765 |
766 |
767 | /**
768 | * Executes the pending callbacks of a resolved Promise after a timeout.
769 | *
770 | * Section 2.2.4 of the Promises/A+ specification requires that Promise
771 | * callbacks must only be invoked from a call stack that only contains Promise
772 | * implementation code, which we accomplish by invoking callback execution after
773 | * a timeout. If {@code startExecution_} is called multiple times for the same
774 | * Promise, the callback chain will be evaluated only once. Additional callbacks
775 | * may be added during the evaluation phase, and will be executed in the same
776 | * event loop.
777 | *
778 | * All Promises added to the waiting list during the same browser event loop
779 | * will be executed in one batch to avoid using a separate timeout per Promise.
780 | *
781 | * @private
782 | */
783 | goog.Promise.prototype.scheduleCallbacks_ = function() {
784 | if (!this.executing_) {
785 | this.executing_ = true;
786 | goog.async.run(this.executeCallbacks_, this);
787 | }
788 | };
789 |
790 |
791 | /**
792 | * Executes all pending callbacks for this Promise.
793 | *
794 | * @private
795 | */
796 | goog.Promise.prototype.executeCallbacks_ = function() {
797 | while (this.callbackEntries_ && this.callbackEntries_.length) {
798 | var entries = this.callbackEntries_;
799 | this.callbackEntries_ = [];
800 |
801 | for (var i = 0; i < entries.length; i++) {
802 | if (goog.Promise.LONG_STACK_TRACES) {
803 | this.currentStep_++;
804 | }
805 | this.executeCallback_(entries[i], this.state_, this.result_);
806 | }
807 | }
808 | this.executing_ = false;
809 | };
810 |
811 |
812 | /**
813 | * Executes a pending callback for this Promise. Invokes an {@code onFulfilled}
814 | * or {@code onRejected} callback based on the resolved state of the Promise.
815 | *
816 | * @param {!goog.Promise.CallbackEntry_} callbackEntry An entry containing the
817 | * onFulfilled and/or onRejected callbacks for this step.
818 | * @param {goog.Promise.State_} state The resolution status of the Promise,
819 | * either FULFILLED or REJECTED.
820 | * @param {*} result The resolved result of the Promise.
821 | * @private
822 | */
823 | goog.Promise.prototype.executeCallback_ = function(
824 | callbackEntry, state, result) {
825 | if (state == goog.Promise.State_.FULFILLED) {
826 | callbackEntry.onFulfilled(result);
827 | } else {
828 | if (callbackEntry.child) {
829 | this.removeUnhandledRejection_();
830 | }
831 | callbackEntry.onRejected(result);
832 | }
833 | };
834 |
835 |
836 | /**
837 | * Records a stack trace entry for functions that call {@code then} or the
838 | * Promise constructor. May be disabled by unsetting {@code LONG_STACK_TRACES}.
839 | *
840 | * @param {!Error} err An Error object created by the calling function for
841 | * providing a stack trace.
842 | * @private
843 | */
844 | goog.Promise.prototype.addStackTrace_ = function(err) {
845 | if (goog.Promise.LONG_STACK_TRACES && goog.isString(err.stack)) {
846 | // Extract the third line of the stack trace, which is the entry for the
847 | // user function that called into Promise code.
848 | var trace = err.stack.split('\n', 4)[3];
849 | var message = err.message;
850 |
851 | // Pad the message to align the traces.
852 | message += Array(11 - message.length).join(' ');
853 | this.stack_.push(message + trace);
854 | }
855 | };
856 |
857 |
858 | /**
859 | * Adds extra stack trace information to an exception for the list of
860 | * asynchronous {@code then} calls that have been run for this Promise. Stack
861 | * trace information is recorded in {@see #addStackTrace_}, and appended to
862 | * rethrown errors when {@code LONG_STACK_TRACES} is enabled.
863 | *
864 | * @param {*} err An unhandled exception captured during callback execution.
865 | * @private
866 | */
867 | goog.Promise.prototype.appendLongStack_ = function(err) {
868 | if (goog.Promise.LONG_STACK_TRACES &&
869 | err && goog.isString(err.stack) && this.stack_.length) {
870 | var longTrace = ['Promise trace:'];
871 |
872 | for (var promise = this; promise; promise = promise.parent_) {
873 | for (var i = this.currentStep_; i >= 0; i--) {
874 | longTrace.push(promise.stack_[i]);
875 | }
876 | longTrace.push('Value: ' +
877 | '[' + (promise.state_ == goog.Promise.State_.REJECTED ?
878 | 'REJECTED' : 'FULFILLED') + '] ' +
879 | '<' + String(promise.result_) + '>');
880 | }
881 | err.stack += '\n\n' + longTrace.join('\n');
882 | }
883 | };
884 |
885 |
886 | /**
887 | * Marks this rejected Promise as having being handled. Also marks any parent
888 | * Promises in the rejected state as handled. The rejection handler will no
889 | * longer be invoked for this Promise (if it has not been called already).
890 | *
891 | * @private
892 | */
893 | goog.Promise.prototype.removeUnhandledRejection_ = function() {
894 | if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {
895 | for (var p = this; p && p.unhandledRejectionId_; p = p.parent_) {
896 | goog.global.clearTimeout(p.unhandledRejectionId_);
897 | p.unhandledRejectionId_ = 0;
898 | }
899 | } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {
900 | for (var p = this; p && p.hadUnhandledRejection_; p = p.parent_) {
901 | p.hadUnhandledRejection_ = false;
902 | }
903 | }
904 | };
905 |
906 |
907 | /**
908 | * Marks this rejected Promise as unhandled. If no {@code onRejected} callback
909 | * is called for this Promise before the {@code UNHANDLED_REJECTION_DELAY}
910 | * expires, the reason will be passed to the unhandled rejection handler. The
911 | * handler typically rethrows the rejection reason so that it becomes visible in
912 | * the developer console.
913 | *
914 | * @param {!goog.Promise} promise The rejected Promise.
915 | * @param {*} reason The Promise rejection reason.
916 | * @private
917 | */
918 | goog.Promise.addUnhandledRejection_ = function(promise, reason) {
919 | if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {
920 | promise.unhandledRejectionId_ = goog.global.setTimeout(function() {
921 | promise.appendLongStack_(reason);
922 | goog.Promise.handleRejection_.call(null, reason);
923 | }, goog.Promise.UNHANDLED_REJECTION_DELAY);
924 |
925 | } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {
926 | promise.hadUnhandledRejection_ = true;
927 | goog.async.run(function() {
928 | if (promise.hadUnhandledRejection_) {
929 | promise.appendLongStack_(reason);
930 | goog.Promise.handleRejection_.call(null, reason);
931 | }
932 | });
933 | }
934 | };
935 |
936 |
937 | /**
938 | * A method that is invoked with the rejection reasons for Promises that are
939 | * rejected but have no {@code onRejected} callbacks registered yet.
940 | * @type {function(*)}
941 | * @private
942 | */
943 | goog.Promise.handleRejection_ = goog.async.throwException;
944 |
945 |
946 | /**
947 | * Sets a handler that will be called with reasons from unhandled rejected
948 | * Promises. If the rejected Promise (or one of its descendants) has an
949 | * {@code onRejected} callback registered, the rejection will be considered
950 | * handled, and the rejection handler will not be called.
951 | *
952 | * By default, unhandled rejections are rethrown so that the error may be
953 | * captured by the developer console or a {@code window.onerror} handler.
954 | *
955 | * @param {function(*)} handler A function that will be called with reasons from
956 | * rejected Promises. Defaults to {@code goog.async.throwException}.
957 | */
958 | goog.Promise.setUnhandledRejectionHandler = function(handler) {
959 | goog.Promise.handleRejection_ = handler;
960 | };
961 |
962 |
963 |
964 | /**
965 | * Error used as a rejection reason for canceled Promises.
966 | *
967 | * @param {string=} opt_message
968 | * @constructor
969 | * @extends {goog.debug.Error}
970 | * @final
971 | */
972 | goog.Promise.CancellationError = function(opt_message) {
973 | goog.Promise.CancellationError.base(this, 'constructor', opt_message);
974 | };
975 | goog.inherits(goog.Promise.CancellationError, goog.debug.Error);
976 |
977 |
978 | /** @override */
979 | goog.Promise.CancellationError.prototype.name = 'cancel';
980 |
981 |
982 |
983 | /**
984 | * Internal implementation of the resolver interface.
985 | *
986 | * @param {!goog.Promise<TYPE>} promise
987 | * @param {function((TYPE|goog.Promise<TYPE>|Thenable)=)} resolve
988 | * @param {function(*): void} reject
989 | * @implements {goog.promise.Resolver<TYPE>}
990 | * @final @struct
991 | * @constructor
992 | * @private
993 | * @template TYPE
994 | */
995 | goog.Promise.Resolver_ = function(promise, resolve, reject) {
996 | /** @const */
997 | this.promise = promise;
998 |
999 | /** @const */
1000 | this.resolve = resolve;
1001 |
1002 | /** @const */
1003 | this.reject = reject;
1004 | };