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