promise.js 43 KB

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