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