Path: blob/trunk/third_party/closure/goog/promise/promise.js
4590 views
/**1* @license2* Copyright The Closure Library Authors.3* SPDX-License-Identifier: Apache-2.04*/56goog.provide('goog.Promise');78goog.require('goog.Thenable');9goog.require('goog.asserts');10goog.require('goog.async.FreeList');11goog.require('goog.async.run');12goog.require('goog.async.throwException');13goog.require('goog.debug.Error');14goog.require('goog.debug.asyncStackTag');15goog.require('goog.functions');16goog.require('goog.promise.Resolver');17181920/**21* NOTE: This class was created in anticipation of the built-in Promise type22* being standardized and implemented across browsers. Now that Promise is23* available in modern browsers, and is automatically polyfilled by the Closure24* Compiler, by default, most new code should use native `Promise`25* instead of `goog.Promise`. However, `goog.Promise` has the26* concept of cancellation which native Promises do not yet have. So code27* needing cancellation may still want to use `goog.Promise`.28*29* Promises provide a result that may be resolved asynchronously. A Promise may30* be resolved by being fulfilled with a fulfillment value, rejected with a31* rejection reason, or blocked by another Promise. A Promise is said to be32* settled if it is either fulfilled or rejected. Once settled, the Promise33* result is immutable.34*35* Promises may represent results of any type, including undefined. Rejection36* reasons are typically Errors, but may also be of any type. Closure Promises37* allow for optional type annotations that enforce that fulfillment values are38* of the appropriate types at compile time.39*40* The result of a Promise is accessible by calling `then` and registering41* `onFulfilled` and `onRejected` callbacks. Once the Promise42* is settled, the relevant callbacks are invoked with the fulfillment value or43* rejection reason as argument. Callbacks are always invoked in the order they44* were registered, even when additional `then` calls are made from inside45* another callback. A callback is always run asynchronously sometime after the46* scope containing the registering `then` invocation has returned.47*48* If a Promise is resolved with another Promise, the first Promise will block49* until the second is settled, and then assumes the same result as the second50* Promise. This allows Promises to depend on the results of other Promises,51* linking together multiple asynchronous operations.52*53* This implementation is compatible with the Promises/A+ specification and54* passes that specification's conformance test suite. A Closure Promise may be55* resolved with a Promise instance (or sufficiently compatible Promise-like56* object) created by other Promise implementations. From the specification,57* Promise-like objects are known as "Thenables".58*59* @see http://promisesaplus.com/60*61* @param {function(62* this:RESOLVER_CONTEXT,63* function((TYPE|IThenable<TYPE>|Thenable)=),64* function(*=)): void} resolver65* Initialization function that is invoked immediately with `resolve`66* and `reject` functions as arguments. The Promise is resolved or67* rejected with the first argument passed to either function.68* @param {RESOLVER_CONTEXT=} opt_context An optional context for executing the69* resolver function. If unspecified, the resolver function will be executed70* in the default scope.71* @constructor72* @struct73* @final74* @implements {goog.Thenable<TYPE>}75* @template TYPE,RESOLVER_CONTEXT76*/77goog.Promise = function(resolver, opt_context) {78'use strict';79/**80* The internal state of this Promise. Either PENDING, FULFILLED, REJECTED, or81* BLOCKED.82* @private {goog.Promise.State_}83*/84this.state_ = goog.Promise.State_.PENDING;8586/**87* The settled result of the Promise. Immutable once set with either a88* fulfillment value or rejection reason.89* @private {*}90*/91this.result_ = undefined;9293/**94* For Promises created by calling `then()`, the originating parent.95* @private {?goog.Promise}96*/97this.parent_ = null;9899/**100* The linked list of `onFulfilled` and `onRejected` callbacks101* added to this Promise by calls to `then()`.102* @private {?goog.Promise.CallbackEntry_}103*/104this.callbackEntries_ = null;105106/**107* The tail of the linked list of `onFulfilled` and `onRejected`108* callbacks added to this Promise by calls to `then()`.109* @private {?goog.Promise.CallbackEntry_}110*/111this.callbackEntriesTail_ = null;112113/**114* Whether the Promise is in the queue of Promises to execute.115* @private {boolean}116*/117this.executing_ = false;118119if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {120/**121* A timeout ID used when the `UNHANDLED_REJECTION_DELAY` is greater122* than 0 milliseconds. The ID is set when the Promise is rejected, and123* cleared only if an `onRejected` callback is invoked for the124* Promise (or one of its descendants) before the delay is exceeded.125*126* If the rejection is not handled before the timeout completes, the127* rejection reason is passed to the unhandled rejection handler.128* @private {number}129*/130this.unhandledRejectionId_ = 0;131} else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {132/**133* When the `UNHANDLED_REJECTION_DELAY` is set to 0 milliseconds, a134* boolean that is set if the Promise is rejected, and reset to false if an135* `onRejected` callback is invoked for the Promise (or one of its136* descendants). If the rejection is not handled before the next timestep,137* the rejection reason is passed to the unhandled rejection handler.138* @private {boolean}139*/140this.hadUnhandledRejection_ = false;141}142143if (goog.Promise.LONG_STACK_TRACES) {144/**145* A list of stack trace frames pointing to the locations where this Promise146* was created or had callbacks added to it. Saved to add additional context147* to stack traces when an exception is thrown.148* @private {!Array<string>}149*/150this.stack_ = [];151this.addStackTrace_(new Error('created'));152153/**154* Index of the most recently executed stack frame entry.155* @private {number}156*/157this.currentStep_ = 0;158}159160// As an optimization, we can skip this if resolver is161// goog.functions.UNDEFINED. This value is passed internally when creating a162// promise which will be resolved through a more optimized path.163if (resolver != goog.functions.UNDEFINED) {164try {165var self = this;166resolver.call(167opt_context,168function(value) {169'use strict';170self.resolve_(goog.Promise.State_.FULFILLED, value);171},172function(reason) {173'use strict';174if (goog.DEBUG &&175!(reason instanceof goog.Promise.CancellationError)) {176try {177// Promise was rejected. Step up one call frame to see why.178if (reason instanceof Error) {179throw reason;180} else {181throw new Error('Promise rejected.');182}183} catch (e) {184// Only thrown so browser dev tools can catch rejections of185// promises when the option to break on caught exceptions is186// activated.187}188}189self.resolve_(goog.Promise.State_.REJECTED, reason);190});191} catch (e) {192this.resolve_(goog.Promise.State_.REJECTED, e);193}194}195};196197198/**199* @define {boolean} Whether traces of `then` calls should be included in200* exceptions thrown201*/202goog.Promise.LONG_STACK_TRACES =203goog.define('goog.Promise.LONG_STACK_TRACES', false);204205206/**207* @define {number} The delay in milliseconds before a rejected Promise's reason208* is passed to the rejection handler. By default, the rejection handler209* rethrows the rejection reason so that it appears in the developer console or210* `window.onerror` handler.211*212* Rejections are rethrown as quickly as possible by default. A negative value213* disables rejection handling entirely.214*/215goog.Promise.UNHANDLED_REJECTION_DELAY =216goog.define('goog.Promise.UNHANDLED_REJECTION_DELAY', 0);217218219/**220* The possible internal states for a Promise. These states are not directly221* observable to external callers.222* @enum {number}223* @private224*/225goog.Promise.State_ = {226/** The Promise is waiting for resolution. */227PENDING: 0,228229/** The Promise is blocked waiting for the result of another Thenable. */230BLOCKED: 1,231232/** The Promise has been resolved with a fulfillment value. */233FULFILLED: 2,234235/** The Promise has been resolved with a rejection reason. */236REJECTED: 3237};238239240241/**242* Entries in the callback chain. Each call to `then`,243* `thenCatch`, or `thenAlways` creates an entry containing the244* functions that may be invoked once the Promise is settled.245*246* @private @final @struct @constructor247*/248goog.Promise.CallbackEntry_ = function() {249'use strict';250/** @type {?goog.Promise} */251this.child = null;252/** @type {?Function} */253this.onFulfilled = null;254/** @type {?Function} */255this.onRejected = null;256/** @type {?} */257this.context = null;258/** @type {?goog.Promise.CallbackEntry_} */259this.next = null;260261/**262* A boolean value to indicate this is a "thenAlways" callback entry.263* Unlike a normal "then/thenVoid" a "thenAlways doesn't participate264* in "cancel" considerations but is simply an observer and requires265* special handling.266* @type {boolean}267*/268this.always = false;269};270271272/** clear the object prior to reuse */273goog.Promise.CallbackEntry_.prototype.reset = function() {274'use strict';275this.child = null;276this.onFulfilled = null;277this.onRejected = null;278this.context = null;279this.always = false;280};281282283/**284* @define {number} The number of currently unused objects to keep around for285* reuse.286*/287goog.Promise.DEFAULT_MAX_UNUSED =288goog.define('goog.Promise.DEFAULT_MAX_UNUSED', 100);289290291/** @const @private {goog.async.FreeList<!goog.Promise.CallbackEntry_>} */292goog.Promise.freelist_ = new goog.async.FreeList(293function() {294'use strict';295return new goog.Promise.CallbackEntry_();296},297function(item) {298'use strict';299item.reset();300},301goog.Promise.DEFAULT_MAX_UNUSED);302303304/**305* @param {Function} onFulfilled306* @param {Function} onRejected307* @param {?} context308* @return {!goog.Promise.CallbackEntry_}309* @private310*/311goog.Promise.getCallbackEntry_ = function(onFulfilled, onRejected, context) {312'use strict';313var entry = goog.Promise.freelist_.get();314entry.onFulfilled = onFulfilled;315entry.onRejected = onRejected;316entry.context = context;317return entry;318};319320321/**322* @param {!goog.Promise.CallbackEntry_} entry323* @private324*/325goog.Promise.returnEntry_ = function(entry) {326'use strict';327goog.Promise.freelist_.put(entry);328};329330331// NOTE: this is the same template expression as is used for332// goog.IThenable.prototype.then333334335/**336* @param {VALUE=} opt_value337* @return {RESULT} A new Promise that is immediately resolved338* with the given value. If the input value is already a goog.Promise, it339* will be returned immediately without creating a new instance.340* @template VALUE341* @template RESULT := type('goog.Promise',342* cond(isUnknown(VALUE), unknown(),343* mapunion(VALUE, (V) =>344* cond(isTemplatized(V) && sub(rawTypeOf(V), 'IThenable'),345* templateTypeOf(V, 0),346* cond(sub(V, 'Thenable'),347* unknown(),348* V)))))349* =:350*/351goog.Promise.resolve = function(opt_value) {352'use strict';353if (opt_value instanceof goog.Promise) {354// Avoid creating a new object if we already have a promise object355// of the correct type.356return opt_value;357}358359// Passing goog.functions.UNDEFINED will cause the constructor to take an360// optimized path that skips calling the resolver function.361var promise = new goog.Promise(goog.functions.UNDEFINED);362promise.resolve_(goog.Promise.State_.FULFILLED, opt_value);363return promise;364};365366367/**368* @param {*=} opt_reason369* @return {!goog.Promise} A new Promise that is immediately rejected with the370* given reason.371*/372goog.Promise.reject = function(opt_reason) {373'use strict';374return new goog.Promise(function(resolve, reject) {375'use strict';376reject(opt_reason);377});378};379380381/**382* This is identical to383* {@code goog.Promise.resolve(value).then(onFulfilled, onRejected)}, but it384* avoids creating an unnecessary wrapper Promise when `value` is already385* thenable.386*387* @param {?(goog.Thenable<TYPE>|Thenable|TYPE)} value388* @param {function(TYPE): ?} onFulfilled389* @param {function(*): *} onRejected390* @template TYPE391* @private392*/393goog.Promise.resolveThen_ = function(value, onFulfilled, onRejected) {394'use strict';395var isThenable =396goog.Promise.maybeThen_(value, onFulfilled, onRejected, null);397if (!isThenable) {398goog.async.run(goog.partial(onFulfilled, value));399}400};401402403/**404* @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}405* promises406* @return {!goog.Promise<TYPE>} A Promise that receives the result of the407* first Promise (or Promise-like) input to settle immediately after it408* settles.409* @template TYPE410*/411goog.Promise.race = function(promises) {412'use strict';413return new goog.Promise(function(resolve, reject) {414'use strict';415if (!promises.length) {416resolve(undefined);417}418for (var i = 0, promise; i < promises.length; i++) {419promise = promises[i];420goog.Promise.resolveThen_(promise, resolve, reject);421}422});423};424425426/**427* @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}428* promises429* @return {!goog.Promise<!Array<TYPE>>} A Promise that receives a list of430* every fulfilled value once every input Promise (or Promise-like) is431* successfully fulfilled, or is rejected with the first rejection reason432* immediately after it is rejected.433* @template TYPE434*/435goog.Promise.all = function(promises) {436'use strict';437return new goog.Promise(function(resolve, reject) {438'use strict';439var toFulfill = promises.length;440var values = [];441442if (!toFulfill) {443resolve(values);444return;445}446447var onFulfill = function(index, value) {448'use strict';449toFulfill--;450values[index] = value;451if (toFulfill == 0) {452resolve(values);453}454};455456var onReject = function(reason) {457'use strict';458reject(reason);459};460461for (var i = 0, promise; i < promises.length; i++) {462promise = promises[i];463goog.Promise.resolveThen_(promise, goog.partial(onFulfill, i), onReject);464}465});466};467468469/**470* @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}471* promises472* @return {!goog.Promise<!Array<{473* fulfilled: boolean,474* value: (TYPE|undefined),475* reason: (*|undefined)}>>} A Promise that resolves with a list of476* result objects once all input Promises (or Promise-like) have477* settled. Each result object contains a 'fulfilled' boolean indicating478* whether an input Promise was fulfilled or rejected. For fulfilled479* Promises, the resulting value is stored in the 'value' field. For480* rejected Promises, the rejection reason is stored in the 'reason'481* field.482* @template TYPE483*/484goog.Promise.allSettled = function(promises) {485'use strict';486return new goog.Promise(function(resolve, reject) {487'use strict';488var toSettle = promises.length;489var results = [];490491if (!toSettle) {492resolve(results);493return;494}495496var onSettled = function(index, fulfilled, result) {497'use strict';498toSettle--;499results[index] = fulfilled ? {fulfilled: true, value: result} :500{fulfilled: false, reason: result};501if (toSettle == 0) {502resolve(results);503}504};505506for (var i = 0, promise; i < promises.length; i++) {507promise = promises[i];508goog.Promise.resolveThen_(509promise, goog.partial(onSettled, i, true /* fulfilled */),510goog.partial(onSettled, i, false /* fulfilled */));511}512});513};514515516/**517* @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}518* promises519* @return {!goog.Promise<TYPE>} A Promise that receives the value of the first520* input to be fulfilled, or is rejected with a list of every rejection521* reason if all inputs are rejected.522* @template TYPE523*/524goog.Promise.firstFulfilled = function(promises) {525'use strict';526return new goog.Promise(function(resolve, reject) {527'use strict';528var toReject = promises.length;529var reasons = [];530531if (!toReject) {532resolve(undefined);533return;534}535536var onFulfill = function(value) {537'use strict';538resolve(value);539};540541var onReject = function(index, reason) {542'use strict';543toReject--;544reasons[index] = reason;545if (toReject == 0) {546reject(reasons);547}548};549550for (var i = 0, promise; i < promises.length; i++) {551promise = promises[i];552goog.Promise.resolveThen_(promise, onFulfill, goog.partial(onReject, i));553}554});555};556557558/**559* @return {!goog.promise.Resolver<TYPE>} Resolver wrapping the promise and its560* resolve / reject functions. Resolving or rejecting the resolver561* resolves or rejects the promise.562* @template TYPE563* @see {@link goog.promise.NativeResolver} for native Promises564*/565goog.Promise.withResolver = function() {566'use strict';567var resolve, reject;568var promise = new goog.Promise(function(rs, rj) {569'use strict';570resolve = rs;571reject = rj;572});573return new goog.Promise.Resolver_(promise, resolve, reject);574};575576577/**578* Adds callbacks that will operate on the result of the Promise, returning a579* new child Promise.580*581* If the Promise is fulfilled, the `onFulfilled` callback will be invoked582* with the fulfillment value as argument, and the child Promise will be583* fulfilled with the return value of the callback. If the callback throws an584* exception, the child Promise will be rejected with the thrown value instead.585*586* If the Promise is rejected, the `onRejected` callback will be invoked587* with the rejection reason as argument, and the child Promise will be resolved588* with the return value or rejected with the thrown value of the callback.589*590* @param {?(function(this:THIS, TYPE): VALUE)=} opt_onFulfilled A591* function that will be invoked with the fulfillment value if the Promise592* is fulfilled.593* @param {?(function(this:THIS, *): *)=} opt_onRejected A function that will594* be invoked with the rejection reason if the Promise is rejected.595* @param {THIS=} opt_context An optional context object that will be the596* execution context for the callbacks. By default, functions are executed597* with the default this.598*599* @return {RESULT} A new Promise that will receive the result600* of the fulfillment or rejection callback.601* @template VALUE602* @template THIS603*604* When a Promise (or thenable) is returned from the fulfilled callback,605* the result is the payload of that promise, not the promise itself.606*607* @template RESULT := type('goog.Promise',608* cond(isUnknown(VALUE), unknown(),609* mapunion(VALUE, (V) =>610* cond(isTemplatized(V) && sub(rawTypeOf(V), 'IThenable'),611* templateTypeOf(V, 0),612* cond(sub(V, 'Thenable'),613* unknown(),614* V)))))615* =:616* @override617*/618goog.Promise.prototype.then = function(619opt_onFulfilled, opt_onRejected, opt_context) {620'use strict';621if (opt_onFulfilled != null) {622goog.asserts.assertFunction(623opt_onFulfilled, 'opt_onFulfilled should be a function.');624}625if (opt_onRejected != null) {626goog.asserts.assertFunction(627opt_onRejected,628'opt_onRejected should be a function. Did you pass opt_context ' +629'as the second argument instead of the third?');630}631632if (goog.Promise.LONG_STACK_TRACES) {633this.addStackTrace_(new Error('then'));634}635636return this.addChildPromise_(637typeof opt_onFulfilled === 'function' ? opt_onFulfilled : null,638typeof opt_onRejected === 'function' ? opt_onRejected : null,639opt_context);640};641goog.Thenable.addImplementation(goog.Promise);642643644/**645* Adds callbacks that will operate on the result of the Promise without646* returning a child Promise (unlike "then").647*648* If the Promise is fulfilled, the `onFulfilled` callback will be invoked649* with the fulfillment value as argument.650*651* If the Promise is rejected, the `onRejected` callback will be invoked652* with the rejection reason as argument.653*654* @param {?(function(this:THIS, TYPE):?)=} opt_onFulfilled A655* function that will be invoked with the fulfillment value if the Promise656* is fulfilled.657* @param {?(function(this:THIS, *): *)=} opt_onRejected A function that will658* be invoked with the rejection reason if the Promise is rejected.659* @param {THIS=} opt_context An optional context object that will be the660* execution context for the callbacks. By default, functions are executed661* with the default this.662* @package663* @template THIS664*/665goog.Promise.prototype.thenVoid = function(666opt_onFulfilled, opt_onRejected, opt_context) {667'use strict';668if (opt_onFulfilled != null) {669goog.asserts.assertFunction(670opt_onFulfilled, 'opt_onFulfilled should be a function.');671}672if (opt_onRejected != null) {673goog.asserts.assertFunction(674opt_onRejected,675'opt_onRejected should be a function. Did you pass opt_context ' +676'as the second argument instead of the third?');677}678679if (goog.Promise.LONG_STACK_TRACES) {680this.addStackTrace_(new Error('then'));681}682683// Note: no default rejection handler is provided here as we need to684// distinguish unhandled rejections.685this.addCallbackEntry_(goog.Promise.getCallbackEntry_(686opt_onFulfilled || (goog.functions.UNDEFINED), opt_onRejected || null,687opt_context));688};689690691/**692* Adds a callback that will be invoked when the Promise is settled (fulfilled693* or rejected). The callback receives no argument, and no new child Promise is694* created. This is useful for ensuring that cleanup takes place after certain695* asynchronous operations. Callbacks added with `thenAlways` will be696* executed in the same order with other calls to `then`,697* `thenAlways`, or `thenCatch`.698*699* Since it does not produce a new child Promise, cancellation propagation is700* not prevented by adding callbacks with `thenAlways`. A Promise that has701* a cleanup handler added with `thenAlways` will be canceled if all of702* its children created by `then` (or `thenCatch`) are canceled.703* Additionally, since any rejections are not passed to the callback, it does704* not stop the unhandled rejection handler from running.705*706* @param {function(this:THIS): void} onSettled A function that will be invoked707* when the Promise is settled (fulfilled or rejected).708* @param {THIS=} opt_context An optional context object that will be the709* execution context for the callbacks. By default, functions are executed710* in the global scope.711* @return {!goog.Promise<TYPE>} This Promise, for chaining additional calls.712* @template THIS713*/714goog.Promise.prototype.thenAlways = function(onSettled, opt_context) {715'use strict';716if (goog.Promise.LONG_STACK_TRACES) {717this.addStackTrace_(new Error('thenAlways'));718}719720var entry = goog.Promise.getCallbackEntry_(onSettled, onSettled, opt_context);721entry.always = true;722this.addCallbackEntry_(entry);723return this;724};725726/**727* Adds a callback that will be invoked only if the Promise is rejected. This728* is equivalent to `then(null, onRejected)`.729*730* Note: Prefer using `catch` which is interoperable with native browser731* Promises.732*733* @param {function(this:THIS, *): *} onRejected A function that will be734* invoked with the rejection reason if this Promise is rejected.735* @param {THIS=} opt_context An optional context object that will be the736* execution context for the callbacks. By default, functions are executed737* in the global scope.738* @return {!goog.Promise} A new Promise that will resolve either to the739* value of this promise, or if this promise is rejected, the result of740* `onRejected`. The returned Promise will reject if `onRejected` throws.741* @template THIS742*/743goog.Promise.prototype.thenCatch = function(onRejected, opt_context) {744'use strict';745if (goog.Promise.LONG_STACK_TRACES) {746this.addStackTrace_(new Error('thenCatch'));747}748return this.addChildPromise_(null, onRejected, opt_context);749};750751/**752* Adds a callback that will be invoked only if the Promise is rejected. This753* is equivalent to `then(null, onRejected)`.754*755* @param {function(this:THIS, *): *} onRejected A function that will be756* invoked with the rejection reason if this Promise is rejected.757* @param {THIS=} opt_context An optional context object that will be the758* execution context for the callbacks. By default, functions are executed759* in the global scope.760* @return {!goog.Promise} A new Promise that will resolve either to the761* value of this promise, or if this promise is rejected, the result of762* `onRejected`. The returned Promise will reject if `onRejected` throws.763* @template THIS764*/765goog.Promise.prototype.catch = goog.Promise.prototype.thenCatch;766767768/**769* Cancels the Promise if it is still pending by rejecting it with a cancel770* Error. No action is performed if the Promise is already resolved.771*772* All child Promises of the canceled Promise will be rejected with the same773* cancel error, as with normal Promise rejection. If the Promise to be canceled774* is the only child of a pending Promise, the parent Promise will also be775* canceled. Cancellation may propagate upward through multiple generations.776*777* @param {string=} opt_message An optional debugging message for describing the778* cancellation reason.779*/780goog.Promise.prototype.cancel = function(opt_message) {781'use strict';782if (this.state_ == goog.Promise.State_.PENDING) {783// Instantiate Error object synchronously. This ensures Error::stack points784// to the cancel() callsite.785var err = new goog.Promise.CancellationError(opt_message);786goog.async.run(function() {787'use strict';788this.cancelInternal_(err);789}, this);790}791};792793794/**795* Cancels this Promise with the given error.796*797* @param {!Error} err The cancellation error.798* @private799*/800goog.Promise.prototype.cancelInternal_ = function(err) {801'use strict';802if (this.state_ == goog.Promise.State_.PENDING) {803if (this.parent_) {804// Cancel the Promise and remove it from the parent's child list.805this.parent_.cancelChild_(this, err);806this.parent_ = null;807} else {808this.resolve_(goog.Promise.State_.REJECTED, err);809}810}811};812813814/**815* Cancels a child Promise from the list of callback entries. If the Promise has816* not already been resolved, reject it with a cancel error. If there are no817* other children in the list of callback entries, propagate the cancellation818* by canceling this Promise as well.819*820* @param {!goog.Promise} childPromise The Promise to cancel.821* @param {!Error} err The cancel error to use for rejecting the Promise.822* @private823*/824goog.Promise.prototype.cancelChild_ = function(childPromise, err) {825'use strict';826if (!this.callbackEntries_) {827return;828}829var childCount = 0;830var childEntry = null;831var beforeChildEntry = null;832833// Find the callback entry for the childPromise, and count whether there are834// additional child Promises.835for (var entry = this.callbackEntries_; entry; entry = entry.next) {836if (!entry.always) {837childCount++;838if (entry.child == childPromise) {839childEntry = entry;840}841if (childEntry && childCount > 1) {842break;843}844}845if (!childEntry) {846beforeChildEntry = entry;847}848}849850// Can a child entry be missing?851852// If the child Promise was the only child, cancel this Promise as well.853// Otherwise, reject only the child Promise with the cancel error.854if (childEntry) {855if (this.state_ == goog.Promise.State_.PENDING && childCount == 1) {856this.cancelInternal_(err);857} else {858if (beforeChildEntry) {859this.removeEntryAfter_(beforeChildEntry);860} else {861this.popEntry_();862}863864this.executeCallback_(childEntry, goog.Promise.State_.REJECTED, err);865}866}867};868869870/**871* Adds a callback entry to the current Promise, and schedules callback872* execution if the Promise has already been settled.873*874* @param {goog.Promise.CallbackEntry_} callbackEntry Record containing875* `onFulfilled` and `onRejected` callbacks to execute after876* the Promise is settled.877* @private878*/879goog.Promise.prototype.addCallbackEntry_ = function(callbackEntry) {880'use strict';881if (!this.hasEntry_() &&882(this.state_ == goog.Promise.State_.FULFILLED ||883this.state_ == goog.Promise.State_.REJECTED)) {884this.scheduleCallbacks_();885}886this.queueEntry_(callbackEntry);887};888889890/**891* Creates a child Promise and adds it to the callback entry list. The result of892* the child Promise is determined by the state of the parent Promise and the893* result of the `onFulfilled` or `onRejected` callbacks as894* specified in the Promise resolution procedure.895*896* @see http://promisesaplus.com/#the__method897*898* @param {?function(this:THIS, TYPE):899* (RESULT|goog.Promise<RESULT>|Thenable)} onFulfilled A callback that900* will be invoked if the Promise is fulfilled, or null.901* @param {?function(this:THIS, *): *} onRejected A callback that will be902* invoked if the Promise is rejected, or null.903* @param {THIS=} opt_context An optional execution context for the callbacks.904* in the default calling context.905* @return {!goog.Promise} The child Promise.906* @template RESULT,THIS907* @private908*/909goog.Promise.prototype.addChildPromise_ = function(910onFulfilled, onRejected, opt_context) {911'use strict';912if (onFulfilled) {913onFulfilled =914goog.debug.asyncStackTag.wrap(onFulfilled, 'goog.Promise.then');915}916if (onRejected) {917onRejected = goog.debug.asyncStackTag.wrap(onRejected, 'goog.Promise.then');918}919920/** @type {goog.Promise.CallbackEntry_} */921var callbackEntry = goog.Promise.getCallbackEntry_(null, null, null);922923callbackEntry.child = new goog.Promise(function(resolve, reject) {924'use strict';925// Invoke onFulfilled, or resolve with the parent's value if absent.926callbackEntry.onFulfilled = onFulfilled ? function(value) {927'use strict';928try {929var result = onFulfilled.call(opt_context, value);930resolve(result);931} catch (err) {932reject(err);933}934} : resolve;935936// Invoke onRejected, or reject with the parent's reason if absent.937callbackEntry.onRejected = onRejected ? function(reason) {938'use strict';939try {940var result = onRejected.call(opt_context, reason);941if (result === undefined &&942reason instanceof goog.Promise.CancellationError) {943// Propagate cancellation to children if no other result is returned.944reject(reason);945} else {946resolve(result);947}948} catch (err) {949reject(err);950}951} : reject;952});953954callbackEntry.child.parent_ = this;955this.addCallbackEntry_(callbackEntry);956return callbackEntry.child;957};958959960/**961* Unblocks the Promise and fulfills it with the given value.962*963* @param {TYPE} value964* @private965*/966goog.Promise.prototype.unblockAndFulfill_ = function(value) {967'use strict';968goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);969this.state_ = goog.Promise.State_.PENDING;970this.resolve_(goog.Promise.State_.FULFILLED, value);971};972973974/**975* Unblocks the Promise and rejects it with the given rejection reason.976*977* @param {*} reason978* @private979*/980goog.Promise.prototype.unblockAndReject_ = function(reason) {981'use strict';982goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);983this.state_ = goog.Promise.State_.PENDING;984this.resolve_(goog.Promise.State_.REJECTED, reason);985};986987988/**989* Attempts to resolve a Promise with a given resolution state and value. This990* is a no-op if the given Promise has already been resolved.991*992* If the given result is a Thenable (such as another Promise), the Promise will993* be settled with the same state and result as the Thenable once it is itself994* settled.995*996* If the given result is not a Thenable, the Promise will be settled (fulfilled997* or rejected) with that result based on the given state.998*999* @see http://promisesaplus.com/#the_promise_resolution_procedure1000*1001* @param {goog.Promise.State_} state1002* @param {*} x The result to apply to the Promise.1003* @private1004*/1005goog.Promise.prototype.resolve_ = function(state, x) {1006'use strict';1007if (this.state_ != goog.Promise.State_.PENDING) {1008return;1009}10101011if (this === x) {1012state = goog.Promise.State_.REJECTED;1013x = new TypeError('Promise cannot resolve to itself');1014}10151016this.state_ = goog.Promise.State_.BLOCKED;1017var isThenable = goog.Promise.maybeThen_(1018x, this.unblockAndFulfill_, this.unblockAndReject_, this);1019if (isThenable) {1020return;1021}10221023this.result_ = x;1024this.state_ = state;1025// Since we can no longer be canceled, remove link to parent, so that the1026// child promise does not keep the parent promise alive.1027this.parent_ = null;1028this.scheduleCallbacks_();10291030if (state == goog.Promise.State_.REJECTED &&1031!(x instanceof goog.Promise.CancellationError)) {1032goog.Promise.addUnhandledRejection_(this, x);1033}1034};103510361037/**1038* Invokes the "then" method of an input value if that value is a Thenable. This1039* is a no-op if the value is not thenable.1040*1041* @param {?} value A potentially thenable value.1042* @param {!Function} onFulfilled1043* @param {!Function} onRejected1044* @param {?} context1045* @return {boolean} Whether the input value was thenable.1046* @private1047*/1048goog.Promise.maybeThen_ = function(value, onFulfilled, onRejected, context) {1049'use strict';1050if (value instanceof goog.Promise) {1051value.thenVoid(onFulfilled, onRejected, context);1052return true;1053} else if (goog.Thenable.isImplementedBy(value)) {1054value = /** @type {!goog.Thenable} */ (value);1055value.then(onFulfilled, onRejected, context);1056return true;1057} else if (goog.isObject(value)) {1058const thenable = /** @type {!Thenable} */ (value);1059try {1060var then = thenable.then;1061if (typeof then === 'function') {1062goog.Promise.tryThen_(thenable, then, onFulfilled, onRejected, context);1063return true;1064}1065} catch (e) {1066onRejected.call(context, e);1067return true;1068}1069}10701071return false;1072};107310741075/**1076* Attempts to call the `then` method on an object in the hopes that it is1077* a Promise-compatible instance. This allows interoperation between different1078* Promise implementations, however a non-compliant object may cause a Promise1079* to hang indefinitely. If the `then` method throws an exception, the1080* dependent Promise will be rejected with the thrown value.1081*1082* @see http://promisesaplus.com/#point-701083*1084* @param {Thenable} thenable An object with a `then` method that may be1085* compatible with the Promise/A+ specification.1086* @param {!Function} then The `then` method of the Thenable object.1087* @param {!Function} onFulfilled1088* @param {!Function} onRejected1089* @param {*} context1090* @private1091*/1092goog.Promise.tryThen_ = function(1093thenable, then, onFulfilled, onRejected, context) {1094'use strict';1095var called = false;1096var resolve = function(value) {1097'use strict';1098if (!called) {1099called = true;1100onFulfilled.call(context, value);1101}1102};11031104var reject = function(reason) {1105'use strict';1106if (!called) {1107called = true;1108onRejected.call(context, reason);1109}1110};11111112try {1113then.call(thenable, resolve, reject);1114} catch (e) {1115reject(e);1116}1117};111811191120/**1121* Executes the pending callbacks of a settled Promise after a timeout.1122*1123* Section 2.2.4 of the Promises/A+ specification requires that Promise1124* callbacks must only be invoked from a call stack that only contains Promise1125* implementation code, which we accomplish by invoking callback execution after1126* a timeout. If `startExecution_` is called multiple times for the same1127* Promise, the callback chain will be evaluated only once. Additional callbacks1128* may be added during the evaluation phase, and will be executed in the same1129* event loop.1130*1131* All Promises added to the waiting list during the same browser event loop1132* will be executed in one batch to avoid using a separate timeout per Promise.1133*1134* @private1135*/1136goog.Promise.prototype.scheduleCallbacks_ = function() {1137'use strict';1138if (!this.executing_) {1139this.executing_ = true;1140goog.async.run(this.executeCallbacks_, this);1141}1142};114311441145/**1146* @return {boolean} Whether there are any pending callbacks queued.1147* @private1148*/1149goog.Promise.prototype.hasEntry_ = function() {1150'use strict';1151return !!this.callbackEntries_;1152};115311541155/**1156* @param {goog.Promise.CallbackEntry_} entry1157* @private1158*/1159goog.Promise.prototype.queueEntry_ = function(entry) {1160'use strict';1161goog.asserts.assert(entry.onFulfilled != null);11621163if (this.callbackEntriesTail_) {1164this.callbackEntriesTail_.next = entry;1165this.callbackEntriesTail_ = entry;1166} else {1167// It the work queue was empty set the head too.1168this.callbackEntries_ = entry;1169this.callbackEntriesTail_ = entry;1170}1171};117211731174/**1175* @return {goog.Promise.CallbackEntry_} entry1176* @private1177*/1178goog.Promise.prototype.popEntry_ = function() {1179'use strict';1180var entry = null;1181if (this.callbackEntries_) {1182entry = this.callbackEntries_;1183this.callbackEntries_ = entry.next;1184entry.next = null;1185}1186// It the work queue is empty clear the tail too.1187if (!this.callbackEntries_) {1188this.callbackEntriesTail_ = null;1189}11901191if (entry != null) {1192goog.asserts.assert(entry.onFulfilled != null);1193}1194return entry;1195};119611971198/**1199* @param {goog.Promise.CallbackEntry_} previous1200* @private1201*/1202goog.Promise.prototype.removeEntryAfter_ = function(previous) {1203'use strict';1204goog.asserts.assert(this.callbackEntries_);1205goog.asserts.assert(previous != null);1206// If the last entry is being removed, update the tail1207if (previous.next == this.callbackEntriesTail_) {1208this.callbackEntriesTail_ = previous;1209}12101211previous.next = previous.next.next;1212};121312141215/**1216* Executes all pending callbacks for this Promise.1217*1218* @private1219*/1220goog.Promise.prototype.executeCallbacks_ = function() {1221'use strict';1222var entry = null;1223while (entry = this.popEntry_()) {1224if (goog.Promise.LONG_STACK_TRACES) {1225this.currentStep_++;1226}1227this.executeCallback_(entry, this.state_, this.result_);1228}1229this.executing_ = false;1230};123112321233/**1234* Executes a pending callback for this Promise. Invokes an `onFulfilled`1235* or `onRejected` callback based on the settled state of the Promise.1236*1237* @param {!goog.Promise.CallbackEntry_} callbackEntry An entry containing the1238* onFulfilled and/or onRejected callbacks for this step.1239* @param {goog.Promise.State_} state The resolution status of the Promise,1240* either FULFILLED or REJECTED.1241* @param {*} result The settled result of the Promise.1242* @private1243*/1244goog.Promise.prototype.executeCallback_ = function(1245callbackEntry, state, result) {1246'use strict';1247// Cancel an unhandled rejection if the then/thenVoid call had an onRejected.1248if (state == goog.Promise.State_.REJECTED && callbackEntry.onRejected &&1249!callbackEntry.always) {1250this.removeUnhandledRejection_();1251}12521253if (callbackEntry.child) {1254// When the parent is settled, the child no longer needs to hold on to it,1255// as the parent can no longer be canceled.1256callbackEntry.child.parent_ = null;1257goog.Promise.invokeCallback_(callbackEntry, state, result);1258} else {1259// Callbacks created with thenAlways or thenVoid do not have the rejection1260// handling code normally set up in the child Promise.1261try {1262callbackEntry.always ?1263callbackEntry.onFulfilled.call(callbackEntry.context) :1264goog.Promise.invokeCallback_(callbackEntry, state, result);1265} catch (err) {1266goog.Promise.handleRejection_.call(null, err);1267}1268}1269goog.Promise.returnEntry_(callbackEntry);1270};127112721273/**1274* Executes the onFulfilled or onRejected callback for a callbackEntry.1275*1276* @param {!goog.Promise.CallbackEntry_} callbackEntry1277* @param {goog.Promise.State_} state1278* @param {*} result1279* @private1280*/1281goog.Promise.invokeCallback_ = function(callbackEntry, state, result) {1282'use strict';1283if (state == goog.Promise.State_.FULFILLED) {1284callbackEntry.onFulfilled.call(callbackEntry.context, result);1285} else if (callbackEntry.onRejected) {1286callbackEntry.onRejected.call(callbackEntry.context, result);1287}1288};128912901291/**1292* Records a stack trace entry for functions that call `then` or the1293* Promise constructor. May be disabled by unsetting `LONG_STACK_TRACES`.1294*1295* @param {!Error} err An Error object created by the calling function for1296* providing a stack trace.1297* @private1298*/1299goog.Promise.prototype.addStackTrace_ = function(err) {1300'use strict';1301if (goog.Promise.LONG_STACK_TRACES && typeof err.stack === 'string') {1302// Extract the third line of the stack trace, which is the entry for the1303// user function that called into Promise code.1304var trace = err.stack.split('\n', 4)[3];1305var message = err.message;13061307// Pad the message to align the traces.1308message += Array(11 - message.length).join(' ');1309this.stack_.push(message + trace);1310}1311};131213131314/**1315* Adds extra stack trace information to an exception for the list of1316* asynchronous `then` calls that have been run for this Promise. Stack1317* trace information is recorded in {@see #addStackTrace_}, and appended to1318* rethrown errors when `LONG_STACK_TRACES` is enabled.1319*1320* @param {?} err An unhandled exception captured during callback execution.1321* @private1322*/1323goog.Promise.prototype.appendLongStack_ = function(err) {1324'use strict';1325if (goog.Promise.LONG_STACK_TRACES && err && typeof err.stack === 'string' &&1326this.stack_.length) {1327var longTrace = ['Promise trace:'];13281329for (var promise = this; promise; promise = promise.parent_) {1330for (var i = this.currentStep_; i >= 0; i--) {1331longTrace.push(promise.stack_[i]);1332}1333longTrace.push(1334'Value: ' +1335'[' + (promise.state_ == goog.Promise.State_.REJECTED ? 'REJECTED' :1336'FULFILLED') +1337'] ' +1338'<' + String(promise.result_) + '>');1339}1340err.stack += '\n\n' + longTrace.join('\n');1341}1342};134313441345/**1346* Marks this rejected Promise as having being handled. Also marks any parent1347* Promises in the rejected state as handled. The rejection handler will no1348* longer be invoked for this Promise (if it has not been called already).1349*1350* @private1351*/1352goog.Promise.prototype.removeUnhandledRejection_ = function() {1353'use strict';1354if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {1355for (var p = this; p && p.unhandledRejectionId_; p = p.parent_) {1356goog.global.clearTimeout(p.unhandledRejectionId_);1357p.unhandledRejectionId_ = 0;1358}1359} else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {1360for (var p = this; p && p.hadUnhandledRejection_; p = p.parent_) {1361p.hadUnhandledRejection_ = false;1362}1363}1364};136513661367/**1368* Marks this rejected Promise as unhandled. If no `onRejected` callback1369* is called for this Promise before the `UNHANDLED_REJECTION_DELAY`1370* expires, the reason will be passed to the unhandled rejection handler. The1371* handler typically rethrows the rejection reason so that it becomes visible in1372* the developer console.1373*1374* @param {!goog.Promise} promise The rejected Promise.1375* @param {*} reason The Promise rejection reason.1376* @private1377*/1378goog.Promise.addUnhandledRejection_ = function(promise, reason) {1379'use strict';1380if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {1381promise.unhandledRejectionId_ = goog.global.setTimeout(function() {1382'use strict';1383promise.appendLongStack_(reason);1384goog.Promise.handleRejection_.call(null, reason);1385}, goog.Promise.UNHANDLED_REJECTION_DELAY);13861387} else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {1388promise.hadUnhandledRejection_ = true;1389goog.async.run(function() {1390'use strict';1391if (promise.hadUnhandledRejection_) {1392promise.appendLongStack_(reason);1393goog.Promise.handleRejection_.call(null, reason);1394}1395});1396}1397};139813991400/**1401* A method that is invoked with the rejection reasons for Promises that are1402* rejected but have no `onRejected` callbacks registered yet.1403* @type {function(*)}1404* @private1405*/1406goog.Promise.handleRejection_ = goog.async.throwException;140714081409/**1410* Sets a handler that will be called with reasons from unhandled rejected1411* Promises. If the rejected Promise (or one of its descendants) has an1412* `onRejected` callback registered, the rejection will be considered1413* handled, and the rejection handler will not be called.1414*1415* By default, unhandled rejections are rethrown so that the error may be1416* captured by the developer console or a `window.onerror` handler.1417*1418* @param {function(*)} handler A function that will be called with reasons from1419* rejected Promises. Defaults to `goog.async.throwException`.1420*/1421goog.Promise.setUnhandledRejectionHandler = function(handler) {1422'use strict';1423goog.Promise.handleRejection_ = handler;1424};1425142614271428/**1429* Error used as a rejection reason for canceled Promises. This will still be1430* a rejection, but should generally be ignored by other error handlers (because1431* cancellation should not be a reportable error).1432*1433* @param {string=} opt_message1434* @constructor1435* @extends {goog.debug.Error}1436* @final1437*/1438goog.Promise.CancellationError = function(opt_message) {1439'use strict';1440goog.Promise.CancellationError.base(this, 'constructor', opt_message);1441this.reportErrorToServer = false;1442};1443goog.inherits(goog.Promise.CancellationError, goog.debug.Error);144414451446/** @override */1447goog.Promise.CancellationError.prototype.name = 'cancel';1448144914501451/**1452* Internal implementation of the resolver interface.1453*1454* @param {!goog.Promise<TYPE>} promise1455* @param {function((TYPE|goog.Promise<TYPE>|Thenable)=)} resolve1456* @param {function(*=): void} reject1457* @implements {goog.promise.Resolver<TYPE>}1458* @final @struct1459* @constructor1460* @private1461* @template TYPE1462*/1463goog.Promise.Resolver_ = function(promise, resolve, reject) {1464'use strict';1465/** @const */1466this.promise = promise;14671468/** @const */1469this.resolve = resolve;14701471/** @const */1472this.reject = reject;1473};147414751476