Path: blob/trunk/third_party/closure/goog/promise/promise.js
2868 views
// Copyright 2013 The Closure Library Authors. All Rights Reserved.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS-IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314goog.provide('goog.Promise');1516goog.require('goog.Thenable');17goog.require('goog.asserts');18goog.require('goog.async.FreeList');19goog.require('goog.async.run');20goog.require('goog.async.throwException');21goog.require('goog.debug.Error');22goog.require('goog.promise.Resolver');23242526/**27* NOTE: This class was created in anticipation of the built-in Promise type28* being standardized and implemented across browsers. Now that Promise is29* available in modern browsers, and is automatically polyfilled by the Closure30* Compiler, by default, most new code should use native {@code Promise}31* instead of {@code goog.Promise}. However, {@code goog.Promise} has the32* concept of cancellation which native Promises do not yet have. So code33* needing cancellation may still want to use {@code goog.Promise}.34*35* Promises provide a result that may be resolved asynchronously. A Promise may36* be resolved by being fulfilled with a fulfillment value, rejected with a37* rejection reason, or blocked by another Promise. A Promise is said to be38* settled if it is either fulfilled or rejected. Once settled, the Promise39* result is immutable.40*41* Promises may represent results of any type, including undefined. Rejection42* reasons are typically Errors, but may also be of any type. Closure Promises43* allow for optional type annotations that enforce that fulfillment values are44* of the appropriate types at compile time.45*46* The result of a Promise is accessible by calling {@code then} and registering47* {@code onFulfilled} and {@code onRejected} callbacks. Once the Promise48* is settled, the relevant callbacks are invoked with the fulfillment value or49* rejection reason as argument. Callbacks are always invoked in the order they50* were registered, even when additional {@code then} calls are made from inside51* another callback. A callback is always run asynchronously sometime after the52* scope containing the registering {@code then} invocation has returned.53*54* If a Promise is resolved with another Promise, the first Promise will block55* until the second is settled, and then assumes the same result as the second56* Promise. This allows Promises to depend on the results of other Promises,57* linking together multiple asynchronous operations.58*59* This implementation is compatible with the Promises/A+ specification and60* passes that specification's conformance test suite. A Closure Promise may be61* resolved with a Promise instance (or sufficiently compatible Promise-like62* object) created by other Promise implementations. From the specification,63* Promise-like objects are known as "Thenables".64*65* @see http://promisesaplus.com/66*67* @param {function(68* this:RESOLVER_CONTEXT,69* function((TYPE|IThenable<TYPE>|Thenable)=),70* function(*=)): void} resolver71* Initialization function that is invoked immediately with {@code resolve}72* and {@code reject} functions as arguments. The Promise is resolved or73* rejected with the first argument passed to either function.74* @param {RESOLVER_CONTEXT=} opt_context An optional context for executing the75* resolver function. If unspecified, the resolver function will be executed76* in the default scope.77* @constructor78* @struct79* @final80* @implements {goog.Thenable<TYPE>}81* @template TYPE,RESOLVER_CONTEXT82*/83goog.Promise = function(resolver, opt_context) {84/**85* The internal state of this Promise. Either PENDING, FULFILLED, REJECTED, or86* BLOCKED.87* @private {goog.Promise.State_}88*/89this.state_ = goog.Promise.State_.PENDING;9091/**92* The settled result of the Promise. Immutable once set with either a93* fulfillment value or rejection reason.94* @private {*}95*/96this.result_ = undefined;9798/**99* For Promises created by calling {@code then()}, the originating parent.100* @private {goog.Promise}101*/102this.parent_ = null;103104/**105* The linked list of {@code onFulfilled} and {@code onRejected} callbacks106* added to this Promise by calls to {@code then()}.107* @private {?goog.Promise.CallbackEntry_}108*/109this.callbackEntries_ = null;110111/**112* The tail of the linked list of {@code onFulfilled} and {@code onRejected}113* callbacks added to this Promise by calls to {@code then()}.114* @private {?goog.Promise.CallbackEntry_}115*/116this.callbackEntriesTail_ = null;117118/**119* Whether the Promise is in the queue of Promises to execute.120* @private {boolean}121*/122this.executing_ = false;123124if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {125/**126* A timeout ID used when the {@code UNHANDLED_REJECTION_DELAY} is greater127* than 0 milliseconds. The ID is set when the Promise is rejected, and128* cleared only if an {@code onRejected} callback is invoked for the129* Promise (or one of its descendants) before the delay is exceeded.130*131* If the rejection is not handled before the timeout completes, the132* rejection reason is passed to the unhandled rejection handler.133* @private {number}134*/135this.unhandledRejectionId_ = 0;136} else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {137/**138* When the {@code UNHANDLED_REJECTION_DELAY} is set to 0 milliseconds, a139* boolean that is set if the Promise is rejected, and reset to false if an140* {@code onRejected} callback is invoked for the Promise (or one of its141* descendants). If the rejection is not handled before the next timestep,142* the rejection reason is passed to the unhandled rejection handler.143* @private {boolean}144*/145this.hadUnhandledRejection_ = false;146}147148if (goog.Promise.LONG_STACK_TRACES) {149/**150* A list of stack trace frames pointing to the locations where this Promise151* was created or had callbacks added to it. Saved to add additional context152* to stack traces when an exception is thrown.153* @private {!Array<string>}154*/155this.stack_ = [];156this.addStackTrace_(new Error('created'));157158/**159* Index of the most recently executed stack frame entry.160* @private {number}161*/162this.currentStep_ = 0;163}164165// As an optimization, we can skip this if resolver is goog.nullFunction.166// This value is passed internally when creating a promise which will be167// resolved through a more optimized path.168if (resolver != goog.nullFunction) {169try {170var self = this;171resolver.call(172opt_context,173function(value) {174self.resolve_(goog.Promise.State_.FULFILLED, value);175},176function(reason) {177if (goog.DEBUG &&178!(reason instanceof goog.Promise.CancellationError)) {179try {180// Promise was rejected. Step up one call frame to see why.181if (reason instanceof Error) {182throw reason;183} else {184throw new Error('Promise rejected.');185}186} catch (e) {187// Only thrown so browser dev tools can catch rejections of188// promises when the option to break on caught exceptions is189// activated.190}191}192self.resolve_(goog.Promise.State_.REJECTED, reason);193});194} catch (e) {195this.resolve_(goog.Promise.State_.REJECTED, e);196}197}198};199200201/**202* @define {boolean} Whether traces of {@code then} calls should be included in203* exceptions thrown204*/205goog.define('goog.Promise.LONG_STACK_TRACES', false);206207208/**209* @define {number} The delay in milliseconds before a rejected Promise's reason210* is passed to the rejection handler. By default, the rejection handler211* rethrows the rejection reason so that it appears in the developer console or212* {@code window.onerror} handler.213*214* Rejections are rethrown as quickly as possible by default. A negative value215* disables rejection handling entirely.216*/217goog.define('goog.Promise.UNHANDLED_REJECTION_DELAY', 0);218219220/**221* The possible internal states for a Promise. These states are not directly222* observable to external callers.223* @enum {number}224* @private225*/226goog.Promise.State_ = {227/** The Promise is waiting for resolution. */228PENDING: 0,229230/** The Promise is blocked waiting for the result of another Thenable. */231BLOCKED: 1,232233/** The Promise has been resolved with a fulfillment value. */234FULFILLED: 2,235236/** The Promise has been resolved with a rejection reason. */237REJECTED: 3238};239240241242/**243* Entries in the callback chain. Each call to {@code then},244* {@code thenCatch}, or {@code thenAlways} creates an entry containing the245* functions that may be invoked once the Promise is settled.246*247* @private @final @struct @constructor248*/249goog.Promise.CallbackEntry_ = function() {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() {274this.child = null;275this.onFulfilled = null;276this.onRejected = null;277this.context = null;278this.always = false;279};280281282/**283* @define {number} The number of currently unused objects to keep around for284* reuse.285*/286goog.define('goog.Promise.DEFAULT_MAX_UNUSED', 100);287288289/** @const @private {goog.async.FreeList<!goog.Promise.CallbackEntry_>} */290goog.Promise.freelist_ = new goog.async.FreeList(291function() { return new goog.Promise.CallbackEntry_(); },292function(item) { item.reset(); }, goog.Promise.DEFAULT_MAX_UNUSED);293294295/**296* @param {Function} onFulfilled297* @param {Function} onRejected298* @param {?} context299* @return {!goog.Promise.CallbackEntry_}300* @private301*/302goog.Promise.getCallbackEntry_ = function(onFulfilled, onRejected, context) {303var entry = goog.Promise.freelist_.get();304entry.onFulfilled = onFulfilled;305entry.onRejected = onRejected;306entry.context = context;307return entry;308};309310311/**312* @param {!goog.Promise.CallbackEntry_} entry313* @private314*/315goog.Promise.returnEntry_ = function(entry) {316goog.Promise.freelist_.put(entry);317};318319320// NOTE: this is the same template expression as is used for321// goog.IThenable.prototype.then322323324/**325* @param {VALUE=} opt_value326* @return {RESULT} A new Promise that is immediately resolved327* with the given value. If the input value is already a goog.Promise, it328* will be returned immediately without creating a new instance.329* @template VALUE330* @template RESULT := type('goog.Promise',331* cond(isUnknown(VALUE), unknown(),332* mapunion(VALUE, (V) =>333* cond(isTemplatized(V) && sub(rawTypeOf(V), 'IThenable'),334* templateTypeOf(V, 0),335* cond(sub(V, 'Thenable'),336* unknown(),337* V)))))338* =:339*/340goog.Promise.resolve = function(opt_value) {341if (opt_value instanceof goog.Promise) {342// Avoid creating a new object if we already have a promise object343// of the correct type.344return opt_value;345}346347// Passing goog.nullFunction will cause the constructor to take an optimized348// path that skips calling the resolver function.349var promise = new goog.Promise(goog.nullFunction);350promise.resolve_(goog.Promise.State_.FULFILLED, opt_value);351return promise;352};353354355/**356* @param {*=} opt_reason357* @return {!goog.Promise} A new Promise that is immediately rejected with the358* given reason.359*/360goog.Promise.reject = function(opt_reason) {361return new goog.Promise(function(resolve, reject) { reject(opt_reason); });362};363364365/**366* This is identical to367* {@code goog.Promise.resolve(value).then(onFulfilled, onRejected)}, but it368* avoids creating an unnecessary wrapper Promise when {@code value} is already369* thenable.370*371* @param {?(goog.Thenable<TYPE>|Thenable|TYPE)} value372* @param {function(TYPE): ?} onFulfilled373* @param {function(*): *} onRejected374* @template TYPE375* @private376*/377goog.Promise.resolveThen_ = function(value, onFulfilled, onRejected) {378var isThenable =379goog.Promise.maybeThen_(value, onFulfilled, onRejected, null);380if (!isThenable) {381goog.async.run(goog.partial(onFulfilled, value));382}383};384385386/**387* @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}388* promises389* @return {!goog.Promise<TYPE>} A Promise that receives the result of the390* first Promise (or Promise-like) input to settle immediately after it391* settles.392* @template TYPE393*/394goog.Promise.race = function(promises) {395return new goog.Promise(function(resolve, reject) {396if (!promises.length) {397resolve(undefined);398}399for (var i = 0, promise; i < promises.length; i++) {400promise = promises[i];401goog.Promise.resolveThen_(promise, resolve, reject);402}403});404};405406407/**408* @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}409* promises410* @return {!goog.Promise<!Array<TYPE>>} A Promise that receives a list of411* every fulfilled value once every input Promise (or Promise-like) is412* successfully fulfilled, or is rejected with the first rejection reason413* immediately after it is rejected.414* @template TYPE415*/416goog.Promise.all = function(promises) {417return new goog.Promise(function(resolve, reject) {418var toFulfill = promises.length;419var values = [];420421if (!toFulfill) {422resolve(values);423return;424}425426var onFulfill = function(index, value) {427toFulfill--;428values[index] = value;429if (toFulfill == 0) {430resolve(values);431}432};433434var onReject = function(reason) { reject(reason); };435436for (var i = 0, promise; i < promises.length; i++) {437promise = promises[i];438goog.Promise.resolveThen_(promise, goog.partial(onFulfill, i), onReject);439}440});441};442443444/**445* @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}446* promises447* @return {!goog.Promise<!Array<{448* fulfilled: boolean,449* value: (TYPE|undefined),450* reason: (*|undefined)}>>} A Promise that resolves with a list of451* result objects once all input Promises (or Promise-like) have452* settled. Each result object contains a 'fulfilled' boolean indicating453* whether an input Promise was fulfilled or rejected. For fulfilled454* Promises, the resulting value is stored in the 'value' field. For455* rejected Promises, the rejection reason is stored in the 'reason'456* field.457* @template TYPE458*/459goog.Promise.allSettled = function(promises) {460return new goog.Promise(function(resolve, reject) {461var toSettle = promises.length;462var results = [];463464if (!toSettle) {465resolve(results);466return;467}468469var onSettled = function(index, fulfilled, result) {470toSettle--;471results[index] = fulfilled ? {fulfilled: true, value: result} :472{fulfilled: false, reason: result};473if (toSettle == 0) {474resolve(results);475}476};477478for (var i = 0, promise; i < promises.length; i++) {479promise = promises[i];480goog.Promise.resolveThen_(481promise, goog.partial(onSettled, i, true /* fulfilled */),482goog.partial(onSettled, i, false /* fulfilled */));483}484});485};486487488/**489* @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}490* promises491* @return {!goog.Promise<TYPE>} A Promise that receives the value of the first492* input to be fulfilled, or is rejected with a list of every rejection493* reason if all inputs are rejected.494* @template TYPE495*/496goog.Promise.firstFulfilled = function(promises) {497return new goog.Promise(function(resolve, reject) {498var toReject = promises.length;499var reasons = [];500501if (!toReject) {502resolve(undefined);503return;504}505506var onFulfill = function(value) { resolve(value); };507508var onReject = function(index, reason) {509toReject--;510reasons[index] = reason;511if (toReject == 0) {512reject(reasons);513}514};515516for (var i = 0, promise; i < promises.length; i++) {517promise = promises[i];518goog.Promise.resolveThen_(promise, onFulfill, goog.partial(onReject, i));519}520});521};522523524/**525* @return {!goog.promise.Resolver<TYPE>} Resolver wrapping the promise and its526* resolve / reject functions. Resolving or rejecting the resolver527* resolves or rejects the promise.528* @template TYPE529*/530goog.Promise.withResolver = function() {531var resolve, reject;532var promise = new goog.Promise(function(rs, rj) {533resolve = rs;534reject = rj;535});536return new goog.Promise.Resolver_(promise, resolve, reject);537};538539540/**541* Adds callbacks that will operate on the result of the Promise, returning a542* new child Promise.543*544* If the Promise is fulfilled, the {@code onFulfilled} callback will be invoked545* with the fulfillment value as argument, and the child Promise will be546* fulfilled with the return value of the callback. If the callback throws an547* exception, the child Promise will be rejected with the thrown value instead.548*549* If the Promise is rejected, the {@code onRejected} callback will be invoked550* with the rejection reason as argument, and the child Promise will be resolved551* with the return value or rejected with the thrown value of the callback.552*553* @override554*/555goog.Promise.prototype.then = function(556opt_onFulfilled, opt_onRejected, opt_context) {557558if (opt_onFulfilled != null) {559goog.asserts.assertFunction(560opt_onFulfilled, 'opt_onFulfilled should be a function.');561}562if (opt_onRejected != null) {563goog.asserts.assertFunction(564opt_onRejected,565'opt_onRejected should be a function. Did you pass opt_context ' +566'as the second argument instead of the third?');567}568569if (goog.Promise.LONG_STACK_TRACES) {570this.addStackTrace_(new Error('then'));571}572573return this.addChildPromise_(574goog.isFunction(opt_onFulfilled) ? opt_onFulfilled : null,575goog.isFunction(opt_onRejected) ? opt_onRejected : null, opt_context);576};577goog.Thenable.addImplementation(goog.Promise);578579580/**581* Adds callbacks that will operate on the result of the Promise without582* returning a child Promise (unlike "then").583*584* If the Promise is fulfilled, the {@code onFulfilled} callback will be invoked585* with the fulfillment value as argument.586*587* If the Promise is rejected, the {@code onRejected} callback will be invoked588* with the rejection reason as argument.589*590* @param {?(function(this:THIS, TYPE):?)=} 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* @package599* @template THIS600*/601goog.Promise.prototype.thenVoid = function(602opt_onFulfilled, opt_onRejected, opt_context) {603604if (opt_onFulfilled != null) {605goog.asserts.assertFunction(606opt_onFulfilled, 'opt_onFulfilled should be a function.');607}608if (opt_onRejected != null) {609goog.asserts.assertFunction(610opt_onRejected,611'opt_onRejected should be a function. Did you pass opt_context ' +612'as the second argument instead of the third?');613}614615if (goog.Promise.LONG_STACK_TRACES) {616this.addStackTrace_(new Error('then'));617}618619// Note: no default rejection handler is provided here as we need to620// distinguish unhandled rejections.621this.addCallbackEntry_(622goog.Promise.getCallbackEntry_(623opt_onFulfilled || goog.nullFunction, opt_onRejected || null,624opt_context));625};626627628/**629* Adds a callback that will be invoked when the Promise is settled (fulfilled630* or rejected). The callback receives no argument, and no new child Promise is631* created. This is useful for ensuring that cleanup takes place after certain632* asynchronous operations. Callbacks added with {@code thenAlways} will be633* executed in the same order with other calls to {@code then},634* {@code thenAlways}, or {@code thenCatch}.635*636* Since it does not produce a new child Promise, cancellation propagation is637* not prevented by adding callbacks with {@code thenAlways}. A Promise that has638* a cleanup handler added with {@code thenAlways} will be canceled if all of639* its children created by {@code then} (or {@code thenCatch}) are canceled.640* Additionally, since any rejections are not passed to the callback, it does641* not stop the unhandled rejection handler from running.642*643* @param {function(this:THIS): void} onSettled A function that will be invoked644* when the Promise is settled (fulfilled or rejected).645* @param {THIS=} opt_context An optional context object that will be the646* execution context for the callbacks. By default, functions are executed647* in the global scope.648* @return {!goog.Promise<TYPE>} This Promise, for chaining additional calls.649* @template THIS650*/651goog.Promise.prototype.thenAlways = function(onSettled, opt_context) {652if (goog.Promise.LONG_STACK_TRACES) {653this.addStackTrace_(new Error('thenAlways'));654}655656var entry = goog.Promise.getCallbackEntry_(onSettled, onSettled, opt_context);657entry.always = true;658this.addCallbackEntry_(entry);659return this;660};661662663/**664* Adds a callback that will be invoked only if the Promise is rejected. This665* is equivalent to {@code then(null, onRejected)}.666*667* @param {function(this:THIS, *): *} onRejected A function that will be668* invoked with the rejection reason if the Promise is rejected.669* @param {THIS=} opt_context An optional context object that will be the670* execution context for the callbacks. By default, functions are executed671* in the global scope.672* @return {!goog.Promise} A new Promise that will receive the result of the673* callback.674* @template THIS675*/676goog.Promise.prototype.thenCatch = function(onRejected, opt_context) {677if (goog.Promise.LONG_STACK_TRACES) {678this.addStackTrace_(new Error('thenCatch'));679}680return this.addChildPromise_(null, onRejected, opt_context);681};682683684/**685* Cancels the Promise if it is still pending by rejecting it with a cancel686* Error. No action is performed if the Promise is already resolved.687*688* All child Promises of the canceled Promise will be rejected with the same689* cancel error, as with normal Promise rejection. If the Promise to be canceled690* is the only child of a pending Promise, the parent Promise will also be691* canceled. Cancellation may propagate upward through multiple generations.692*693* @param {string=} opt_message An optional debugging message for describing the694* cancellation reason.695*/696goog.Promise.prototype.cancel = function(opt_message) {697if (this.state_ == goog.Promise.State_.PENDING) {698goog.async.run(function() {699var err = new goog.Promise.CancellationError(opt_message);700this.cancelInternal_(err);701}, this);702}703};704705706/**707* Cancels this Promise with the given error.708*709* @param {!Error} err The cancellation error.710* @private711*/712goog.Promise.prototype.cancelInternal_ = function(err) {713if (this.state_ == goog.Promise.State_.PENDING) {714if (this.parent_) {715// Cancel the Promise and remove it from the parent's child list.716this.parent_.cancelChild_(this, err);717this.parent_ = null;718} else {719this.resolve_(goog.Promise.State_.REJECTED, err);720}721}722};723724725/**726* Cancels a child Promise from the list of callback entries. If the Promise has727* not already been resolved, reject it with a cancel error. If there are no728* other children in the list of callback entries, propagate the cancellation729* by canceling this Promise as well.730*731* @param {!goog.Promise} childPromise The Promise to cancel.732* @param {!Error} err The cancel error to use for rejecting the Promise.733* @private734*/735goog.Promise.prototype.cancelChild_ = function(childPromise, err) {736if (!this.callbackEntries_) {737return;738}739var childCount = 0;740var childEntry = null;741var beforeChildEntry = null;742743// Find the callback entry for the childPromise, and count whether there are744// additional child Promises.745for (var entry = this.callbackEntries_; entry; entry = entry.next) {746if (!entry.always) {747childCount++;748if (entry.child == childPromise) {749childEntry = entry;750}751if (childEntry && childCount > 1) {752break;753}754}755if (!childEntry) {756beforeChildEntry = entry;757}758}759760// Can a child entry be missing?761762// If the child Promise was the only child, cancel this Promise as well.763// Otherwise, reject only the child Promise with the cancel error.764if (childEntry) {765if (this.state_ == goog.Promise.State_.PENDING && childCount == 1) {766this.cancelInternal_(err);767} else {768if (beforeChildEntry) {769this.removeEntryAfter_(beforeChildEntry);770} else {771this.popEntry_();772}773774this.executeCallback_(childEntry, goog.Promise.State_.REJECTED, err);775}776}777};778779780/**781* Adds a callback entry to the current Promise, and schedules callback782* execution if the Promise has already been settled.783*784* @param {goog.Promise.CallbackEntry_} callbackEntry Record containing785* {@code onFulfilled} and {@code onRejected} callbacks to execute after786* the Promise is settled.787* @private788*/789goog.Promise.prototype.addCallbackEntry_ = function(callbackEntry) {790if (!this.hasEntry_() && (this.state_ == goog.Promise.State_.FULFILLED ||791this.state_ == goog.Promise.State_.REJECTED)) {792this.scheduleCallbacks_();793}794this.queueEntry_(callbackEntry);795};796797798/**799* Creates a child Promise and adds it to the callback entry list. The result of800* the child Promise is determined by the state of the parent Promise and the801* result of the {@code onFulfilled} or {@code onRejected} callbacks as802* specified in the Promise resolution procedure.803*804* @see http://promisesaplus.com/#the__method805*806* @param {?function(this:THIS, TYPE):807* (RESULT|goog.Promise<RESULT>|Thenable)} onFulfilled A callback that808* will be invoked if the Promise is fulfilled, or null.809* @param {?function(this:THIS, *): *} onRejected A callback that will be810* invoked if the Promise is rejected, or null.811* @param {THIS=} opt_context An optional execution context for the callbacks.812* in the default calling context.813* @return {!goog.Promise} The child Promise.814* @template RESULT,THIS815* @private816*/817goog.Promise.prototype.addChildPromise_ = function(818onFulfilled, onRejected, opt_context) {819820/** @type {goog.Promise.CallbackEntry_} */821var callbackEntry = goog.Promise.getCallbackEntry_(null, null, null);822823callbackEntry.child = new goog.Promise(function(resolve, reject) {824// Invoke onFulfilled, or resolve with the parent's value if absent.825callbackEntry.onFulfilled = onFulfilled ? function(value) {826try {827var result = onFulfilled.call(opt_context, value);828resolve(result);829} catch (err) {830reject(err);831}832} : resolve;833834// Invoke onRejected, or reject with the parent's reason if absent.835callbackEntry.onRejected = onRejected ? function(reason) {836try {837var result = onRejected.call(opt_context, reason);838if (!goog.isDef(result) &&839reason instanceof goog.Promise.CancellationError) {840// Propagate cancellation to children if no other result is returned.841reject(reason);842} else {843resolve(result);844}845} catch (err) {846reject(err);847}848} : reject;849});850851callbackEntry.child.parent_ = this;852this.addCallbackEntry_(callbackEntry);853return callbackEntry.child;854};855856857/**858* Unblocks the Promise and fulfills it with the given value.859*860* @param {TYPE} value861* @private862*/863goog.Promise.prototype.unblockAndFulfill_ = function(value) {864goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);865this.state_ = goog.Promise.State_.PENDING;866this.resolve_(goog.Promise.State_.FULFILLED, value);867};868869870/**871* Unblocks the Promise and rejects it with the given rejection reason.872*873* @param {*} reason874* @private875*/876goog.Promise.prototype.unblockAndReject_ = function(reason) {877goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);878this.state_ = goog.Promise.State_.PENDING;879this.resolve_(goog.Promise.State_.REJECTED, reason);880};881882883/**884* Attempts to resolve a Promise with a given resolution state and value. This885* is a no-op if the given Promise has already been resolved.886*887* If the given result is a Thenable (such as another Promise), the Promise will888* be settled with the same state and result as the Thenable once it is itself889* settled.890*891* If the given result is not a Thenable, the Promise will be settled (fulfilled892* or rejected) with that result based on the given state.893*894* @see http://promisesaplus.com/#the_promise_resolution_procedure895*896* @param {goog.Promise.State_} state897* @param {*} x The result to apply to the Promise.898* @private899*/900goog.Promise.prototype.resolve_ = function(state, x) {901if (this.state_ != goog.Promise.State_.PENDING) {902return;903}904905if (this === x) {906state = goog.Promise.State_.REJECTED;907x = new TypeError('Promise cannot resolve to itself');908}909910this.state_ = goog.Promise.State_.BLOCKED;911var isThenable = goog.Promise.maybeThen_(912x, this.unblockAndFulfill_, this.unblockAndReject_, this);913if (isThenable) {914return;915}916917this.result_ = x;918this.state_ = state;919// Since we can no longer be canceled, remove link to parent, so that the920// child promise does not keep the parent promise alive.921this.parent_ = null;922this.scheduleCallbacks_();923924if (state == goog.Promise.State_.REJECTED &&925!(x instanceof goog.Promise.CancellationError)) {926goog.Promise.addUnhandledRejection_(this, x);927}928};929930931/**932* Invokes the "then" method of an input value if that value is a Thenable. This933* is a no-op if the value is not thenable.934*935* @param {?} value A potentially thenable value.936* @param {!Function} onFulfilled937* @param {!Function} onRejected938* @param {?} context939* @return {boolean} Whether the input value was thenable.940* @private941*/942goog.Promise.maybeThen_ = function(value, onFulfilled, onRejected, context) {943if (value instanceof goog.Promise) {944value.thenVoid(onFulfilled, onRejected, context);945return true;946} else if (goog.Thenable.isImplementedBy(value)) {947value = /** @type {!goog.Thenable} */ (value);948value.then(onFulfilled, onRejected, context);949return true;950} else if (goog.isObject(value)) {951try {952var then = value['then'];953if (goog.isFunction(then)) {954goog.Promise.tryThen_(value, then, onFulfilled, onRejected, context);955return true;956}957} catch (e) {958onRejected.call(context, e);959return true;960}961}962963return false;964};965966967/**968* Attempts to call the {@code then} method on an object in the hopes that it is969* a Promise-compatible instance. This allows interoperation between different970* Promise implementations, however a non-compliant object may cause a Promise971* to hang indefinitely. If the {@code then} method throws an exception, the972* dependent Promise will be rejected with the thrown value.973*974* @see http://promisesaplus.com/#point-70975*976* @param {Thenable} thenable An object with a {@code then} method that may be977* compatible with the Promise/A+ specification.978* @param {!Function} then The {@code then} method of the Thenable object.979* @param {!Function} onFulfilled980* @param {!Function} onRejected981* @param {*} context982* @private983*/984goog.Promise.tryThen_ = function(985thenable, then, onFulfilled, onRejected, context) {986987var called = false;988var resolve = function(value) {989if (!called) {990called = true;991onFulfilled.call(context, value);992}993};994995var reject = function(reason) {996if (!called) {997called = true;998onRejected.call(context, reason);999}1000};10011002try {1003then.call(thenable, resolve, reject);1004} catch (e) {1005reject(e);1006}1007};100810091010/**1011* Executes the pending callbacks of a settled Promise after a timeout.1012*1013* Section 2.2.4 of the Promises/A+ specification requires that Promise1014* callbacks must only be invoked from a call stack that only contains Promise1015* implementation code, which we accomplish by invoking callback execution after1016* a timeout. If {@code startExecution_} is called multiple times for the same1017* Promise, the callback chain will be evaluated only once. Additional callbacks1018* may be added during the evaluation phase, and will be executed in the same1019* event loop.1020*1021* All Promises added to the waiting list during the same browser event loop1022* will be executed in one batch to avoid using a separate timeout per Promise.1023*1024* @private1025*/1026goog.Promise.prototype.scheduleCallbacks_ = function() {1027if (!this.executing_) {1028this.executing_ = true;1029goog.async.run(this.executeCallbacks_, this);1030}1031};103210331034/**1035* @return {boolean} Whether there are any pending callbacks queued.1036* @private1037*/1038goog.Promise.prototype.hasEntry_ = function() {1039return !!this.callbackEntries_;1040};104110421043/**1044* @param {goog.Promise.CallbackEntry_} entry1045* @private1046*/1047goog.Promise.prototype.queueEntry_ = function(entry) {1048goog.asserts.assert(entry.onFulfilled != null);10491050if (this.callbackEntriesTail_) {1051this.callbackEntriesTail_.next = entry;1052this.callbackEntriesTail_ = entry;1053} else {1054// It the work queue was empty set the head too.1055this.callbackEntries_ = entry;1056this.callbackEntriesTail_ = entry;1057}1058};105910601061/**1062* @return {goog.Promise.CallbackEntry_} entry1063* @private1064*/1065goog.Promise.prototype.popEntry_ = function() {1066var entry = null;1067if (this.callbackEntries_) {1068entry = this.callbackEntries_;1069this.callbackEntries_ = entry.next;1070entry.next = null;1071}1072// It the work queue is empty clear the tail too.1073if (!this.callbackEntries_) {1074this.callbackEntriesTail_ = null;1075}10761077if (entry != null) {1078goog.asserts.assert(entry.onFulfilled != null);1079}1080return entry;1081};108210831084/**1085* @param {goog.Promise.CallbackEntry_} previous1086* @private1087*/1088goog.Promise.prototype.removeEntryAfter_ = function(previous) {1089goog.asserts.assert(this.callbackEntries_);1090goog.asserts.assert(previous != null);1091// If the last entry is being removed, update the tail1092if (previous.next == this.callbackEntriesTail_) {1093this.callbackEntriesTail_ = previous;1094}10951096previous.next = previous.next.next;1097};109810991100/**1101* Executes all pending callbacks for this Promise.1102*1103* @private1104*/1105goog.Promise.prototype.executeCallbacks_ = function() {1106var entry = null;1107while (entry = this.popEntry_()) {1108if (goog.Promise.LONG_STACK_TRACES) {1109this.currentStep_++;1110}1111this.executeCallback_(entry, this.state_, this.result_);1112}1113this.executing_ = false;1114};111511161117/**1118* Executes a pending callback for this Promise. Invokes an {@code onFulfilled}1119* or {@code onRejected} callback based on the settled state of the Promise.1120*1121* @param {!goog.Promise.CallbackEntry_} callbackEntry An entry containing the1122* onFulfilled and/or onRejected callbacks for this step.1123* @param {goog.Promise.State_} state The resolution status of the Promise,1124* either FULFILLED or REJECTED.1125* @param {*} result The settled result of the Promise.1126* @private1127*/1128goog.Promise.prototype.executeCallback_ = function(1129callbackEntry, state, result) {1130// Cancel an unhandled rejection if the then/thenVoid call had an onRejected.1131if (state == goog.Promise.State_.REJECTED && callbackEntry.onRejected &&1132!callbackEntry.always) {1133this.removeUnhandledRejection_();1134}11351136if (callbackEntry.child) {1137// When the parent is settled, the child no longer needs to hold on to it,1138// as the parent can no longer be canceled.1139callbackEntry.child.parent_ = null;1140goog.Promise.invokeCallback_(callbackEntry, state, result);1141} else {1142// Callbacks created with thenAlways or thenVoid do not have the rejection1143// handling code normally set up in the child Promise.1144try {1145callbackEntry.always ?1146callbackEntry.onFulfilled.call(callbackEntry.context) :1147goog.Promise.invokeCallback_(callbackEntry, state, result);1148} catch (err) {1149goog.Promise.handleRejection_.call(null, err);1150}1151}1152goog.Promise.returnEntry_(callbackEntry);1153};115411551156/**1157* Executes the onFulfilled or onRejected callback for a callbackEntry.1158*1159* @param {!goog.Promise.CallbackEntry_} callbackEntry1160* @param {goog.Promise.State_} state1161* @param {*} result1162* @private1163*/1164goog.Promise.invokeCallback_ = function(callbackEntry, state, result) {1165if (state == goog.Promise.State_.FULFILLED) {1166callbackEntry.onFulfilled.call(callbackEntry.context, result);1167} else if (callbackEntry.onRejected) {1168callbackEntry.onRejected.call(callbackEntry.context, result);1169}1170};117111721173/**1174* Records a stack trace entry for functions that call {@code then} or the1175* Promise constructor. May be disabled by unsetting {@code LONG_STACK_TRACES}.1176*1177* @param {!Error} err An Error object created by the calling function for1178* providing a stack trace.1179* @private1180*/1181goog.Promise.prototype.addStackTrace_ = function(err) {1182if (goog.Promise.LONG_STACK_TRACES && goog.isString(err.stack)) {1183// Extract the third line of the stack trace, which is the entry for the1184// user function that called into Promise code.1185var trace = err.stack.split('\n', 4)[3];1186var message = err.message;11871188// Pad the message to align the traces.1189message += Array(11 - message.length).join(' ');1190this.stack_.push(message + trace);1191}1192};119311941195/**1196* Adds extra stack trace information to an exception for the list of1197* asynchronous {@code then} calls that have been run for this Promise. Stack1198* trace information is recorded in {@see #addStackTrace_}, and appended to1199* rethrown errors when {@code LONG_STACK_TRACES} is enabled.1200*1201* @param {*} err An unhandled exception captured during callback execution.1202* @private1203*/1204goog.Promise.prototype.appendLongStack_ = function(err) {1205if (goog.Promise.LONG_STACK_TRACES && err && goog.isString(err.stack) &&1206this.stack_.length) {1207var longTrace = ['Promise trace:'];12081209for (var promise = this; promise; promise = promise.parent_) {1210for (var i = this.currentStep_; i >= 0; i--) {1211longTrace.push(promise.stack_[i]);1212}1213longTrace.push(1214'Value: ' +1215'[' + (promise.state_ == goog.Promise.State_.REJECTED ? 'REJECTED' :1216'FULFILLED') +1217'] ' +1218'<' + String(promise.result_) + '>');1219}1220err.stack += '\n\n' + longTrace.join('\n');1221}1222};122312241225/**1226* Marks this rejected Promise as having being handled. Also marks any parent1227* Promises in the rejected state as handled. The rejection handler will no1228* longer be invoked for this Promise (if it has not been called already).1229*1230* @private1231*/1232goog.Promise.prototype.removeUnhandledRejection_ = function() {1233if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {1234for (var p = this; p && p.unhandledRejectionId_; p = p.parent_) {1235goog.global.clearTimeout(p.unhandledRejectionId_);1236p.unhandledRejectionId_ = 0;1237}1238} else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {1239for (var p = this; p && p.hadUnhandledRejection_; p = p.parent_) {1240p.hadUnhandledRejection_ = false;1241}1242}1243};124412451246/**1247* Marks this rejected Promise as unhandled. If no {@code onRejected} callback1248* is called for this Promise before the {@code UNHANDLED_REJECTION_DELAY}1249* expires, the reason will be passed to the unhandled rejection handler. The1250* handler typically rethrows the rejection reason so that it becomes visible in1251* the developer console.1252*1253* @param {!goog.Promise} promise The rejected Promise.1254* @param {*} reason The Promise rejection reason.1255* @private1256*/1257goog.Promise.addUnhandledRejection_ = function(promise, reason) {1258if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {1259promise.unhandledRejectionId_ = goog.global.setTimeout(function() {1260promise.appendLongStack_(reason);1261goog.Promise.handleRejection_.call(null, reason);1262}, goog.Promise.UNHANDLED_REJECTION_DELAY);12631264} else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {1265promise.hadUnhandledRejection_ = true;1266goog.async.run(function() {1267if (promise.hadUnhandledRejection_) {1268promise.appendLongStack_(reason);1269goog.Promise.handleRejection_.call(null, reason);1270}1271});1272}1273};127412751276/**1277* A method that is invoked with the rejection reasons for Promises that are1278* rejected but have no {@code onRejected} callbacks registered yet.1279* @type {function(*)}1280* @private1281*/1282goog.Promise.handleRejection_ = goog.async.throwException;128312841285/**1286* Sets a handler that will be called with reasons from unhandled rejected1287* Promises. If the rejected Promise (or one of its descendants) has an1288* {@code onRejected} callback registered, the rejection will be considered1289* handled, and the rejection handler will not be called.1290*1291* By default, unhandled rejections are rethrown so that the error may be1292* captured by the developer console or a {@code window.onerror} handler.1293*1294* @param {function(*)} handler A function that will be called with reasons from1295* rejected Promises. Defaults to {@code goog.async.throwException}.1296*/1297goog.Promise.setUnhandledRejectionHandler = function(handler) {1298goog.Promise.handleRejection_ = handler;1299};1300130113021303/**1304* Error used as a rejection reason for canceled Promises.1305*1306* @param {string=} opt_message1307* @constructor1308* @extends {goog.debug.Error}1309* @final1310*/1311goog.Promise.CancellationError = function(opt_message) {1312goog.Promise.CancellationError.base(this, 'constructor', opt_message);1313};1314goog.inherits(goog.Promise.CancellationError, goog.debug.Error);131513161317/** @override */1318goog.Promise.CancellationError.prototype.name = 'cancel';1319132013211322/**1323* Internal implementation of the resolver interface.1324*1325* @param {!goog.Promise<TYPE>} promise1326* @param {function((TYPE|goog.Promise<TYPE>|Thenable)=)} resolve1327* @param {function(*=): void} reject1328* @implements {goog.promise.Resolver<TYPE>}1329* @final @struct1330* @constructor1331* @private1332* @template TYPE1333*/1334goog.Promise.Resolver_ = function(promise, resolve, reject) {1335/** @const */1336this.promise = promise;13371338/** @const */1339this.resolve = resolve;13401341/** @const */1342this.reject = reject;1343};134413451346