-
-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
promise.js
2638 lines (2299 loc) · 78.5 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
// Copyright 2011 Software Freedom Conservancy. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @license Portions of this code are from the Dojo toolkit, received under the
* BSD License:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the Dojo Foundation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview A promise implementation based on the CommonJS promise/A and
* promise/B proposals. For more information, see
* http://wiki.commonjs.org/wiki/Promises.
*/
goog.provide('webdriver.promise');
goog.provide('webdriver.promise.ControlFlow');
goog.provide('webdriver.promise.Deferred');
goog.provide('webdriver.promise.Promise');
goog.provide('webdriver.promise.Thenable');
goog.require('goog.array');
goog.require('goog.async.run');
goog.require('goog.async.throwException');
goog.require('goog.debug.Error');
goog.require('goog.object');
goog.require('webdriver.EventEmitter');
goog.require('webdriver.stacktrace.Snapshot');
goog.require('webdriver.stacktrace');
/**
* @define {boolean} Whether to append traces of {@code then} to rejection
* errors.
*/
goog.define('webdriver.promise.LONG_STACK_TRACES', false);
goog.scope(function() {
var promise = webdriver.promise;
/**
* Generates an error to capture the current stack trace.
* @param {string} name Error name for this stack trace.
* @param {string} msg Message to record.
* @param {!Function} topFn The function that should appear at the top of the
* stack; only applicable in V8.
* @return {!Error} The generated error.
*/
promise.captureStackTrace = function(name, msg, topFn) {
var e = Error(msg);
e.name = name;
if (Error.captureStackTrace) {
Error.captureStackTrace(e, topFn);
} else {
var stack = webdriver.stacktrace.getStack(e);
e.stack = e.toString();
if (stack) {
e.stack += '\n' + stack;
}
}
return e;
};
/**
* Error used when the computation of a promise is cancelled.
*
* @param {string=} opt_msg The cancellation message.
* @constructor
* @extends {goog.debug.Error}
* @final
*/
promise.CancellationError = function(opt_msg) {
goog.debug.Error.call(this, opt_msg);
/** @override */
this.name = 'CancellationError';
};
goog.inherits(promise.CancellationError, goog.debug.Error);
/**
* Wraps the given error in a CancellationError. Will trivially return
* the error itself if it is an instanceof CancellationError.
*
* @param {*} error The error to wrap.
* @param {string=} opt_msg The prefix message to use.
* @return {!promise.CancellationError} A cancellation error.
*/
promise.CancellationError.wrap = function(error, opt_msg) {
if (error instanceof promise.CancellationError) {
return /** @type {!promise.CancellationError} */(error);
} else if (opt_msg) {
var message = opt_msg;
if (error) {
message += ': ' + error;
}
return new promise.CancellationError(message);
}
var message;
if (error) {
message = error + '';
}
return new promise.CancellationError(message);
};
/**
* Thenable is a promise-like object with a {@code then} method which may be
* used to schedule callbacks on a promised value.
*
* @interface
* @extends {IThenable<T>}
* @template T
*/
promise.Thenable = function() {};
/**
* Cancels the computation of this promise's value, rejecting the promise in the
* process. This method is a no-op if the promise has alreayd been resolved.
*
* @param {(string|promise.CancellationError)=} opt_reason The reason this
* promise is being cancelled.
*/
promise.Thenable.prototype.cancel = function(opt_reason) {};
/** @return {boolean} Whether this promise's value is still being computed. */
promise.Thenable.prototype.isPending = function() {};
/**
* Registers listeners for when this instance is resolved.
*
* @param {?(function(T): (R|IThenable<R>))=} opt_callback The
* function to call if this promise is successfully resolved. The function
* should expect a single argument: the promise's resolved value.
* @param {?(function(*): (R|IThenable<R>))=} opt_errback
* The function to call if this promise is rejected. The function should
* expect a single argument: the rejection reason.
* @return {!promise.Promise<R>} A new promise which will be
* resolved with the result of the invoked callback.
* @template R
*/
promise.Thenable.prototype.then = function(opt_callback, opt_errback) {};
/**
* Registers a listener for when this promise is rejected. This is synonymous
* with the {@code catch} clause in a synchronous API:
* <pre><code>
* // Synchronous API:
* try {
* doSynchronousWork();
* } catch (ex) {
* console.error(ex);
* }
*
* // Asynchronous promise API:
* doAsynchronousWork().thenCatch(function(ex) {
* console.error(ex);
* });
* </code></pre>
*
* @param {function(*): (R|IThenable<R>)} errback The
* function to call if this promise is rejected. The function should
* expect a single argument: the rejection reason.
* @return {!promise.Promise<R>} A new promise which will be
* resolved with the result of the invoked callback.
* @template R
*/
promise.Thenable.prototype.thenCatch = function(errback) {};
/**
* Registers a listener to invoke when this promise is resolved, regardless
* of whether the promise's value was successfully computed. This function
* is synonymous with the {@code finally} clause in a synchronous API:
* <pre><code>
* // Synchronous API:
* try {
* doSynchronousWork();
* } finally {
* cleanUp();
* }
*
* // Asynchronous promise API:
* doAsynchronousWork().thenFinally(cleanUp);
* </code></pre>
*
* <b>Note:</b> similar to the {@code finally} clause, if the registered
* callback returns a rejected promise or throws an error, it will silently
* replace the rejection error (if any) from this promise:
* <pre><code>
* try {
* throw Error('one');
* } finally {
* throw Error('two'); // Hides Error: one
* }
*
* promise.rejected(Error('one'))
* .thenFinally(function() {
* throw Error('two'); // Hides Error: one
* });
* </code></pre>
*
*
* @param {function(): (R|IThenable<R>)} callback The function
* to call when this promise is resolved.
* @return {!promise.Promise<R>} A promise that will be fulfilled
* with the callback result.
* @template R
*/
promise.Thenable.prototype.thenFinally = function(callback) {};
/**
* Property used to flag constructor's as implementing the Thenable interface
* for runtime type checking.
* @private {string}
* @const
*/
promise.Thenable.IMPLEMENTED_BY_PROP_ = '$webdriver_Thenable';
/**
* Adds a property to a class prototype to allow runtime checks of whether
* instances of that class implement the Thenable interface. This function will
* also ensure the prototype's {@code then} function is exported from compiled
* code.
* @param {function(new: promise.Thenable, ...?)} ctor The
* constructor whose prototype to modify.
*/
promise.Thenable.addImplementation = function(ctor) {
// Based on goog.promise.Thenable.isImplementation.
ctor.prototype['then'] = ctor.prototype.then;
try {
// Old IE7 does not support defineProperty; IE8 only supports it for
// DOM elements.
Object.defineProperty(
ctor.prototype,
promise.Thenable.IMPLEMENTED_BY_PROP_,
{'value': true, 'enumerable': false});
} catch (ex) {
ctor.prototype[promise.Thenable.IMPLEMENTED_BY_PROP_] = true;
}
};
/**
* Checks if an object has been tagged for implementing the Thenable interface
* as defined by {@link promise.Thenable.addImplementation}.
* @param {*} object The object to test.
* @return {boolean} Whether the object is an implementation of the Thenable
* interface.
*/
promise.Thenable.isImplementation = function(object) {
// Based on goog.promise.Thenable.isImplementation.
if (!object) {
return false;
}
try {
return !!object[promise.Thenable.IMPLEMENTED_BY_PROP_];
} catch (e) {
return false; // Property access seems to be forbidden.
}
};
/**
* Represents the eventual value of a completed operation. Each promise may be
* in one of three states: pending, fulfilled, or rejected. Each promise starts
* in the pending state and may make a single transition to either a
* fulfilled or rejected state, at which point the promise is considered
* resolved.
*
* @param {function(
* function((T|IThenable<T>|Thenable)=),
* function(*=))} resolver
* Function that is invoked immediately to begin computation of this
* promise's value. The function should accept a pair of callback functions,
* one for fulfilling the promise and another for rejecting it.
* @param {promise.ControlFlow=} opt_flow The control flow
* this instance was created under. Defaults to the currently active flow.
* @constructor
* @implements {promise.Thenable<T>}
* @template T
* @see http://promises-aplus.github.io/promises-spec/
*/
promise.Promise = function(resolver, opt_flow) {
goog.getUid(this);
/** @private {!promise.ControlFlow} */
this.flow_ = opt_flow || promise.controlFlow();
/** @private {Error} */
this.stack_ = null;
if (promise.LONG_STACK_TRACES) {
this.stack_ = promise.captureStackTrace('Promise', 'new', promise.Promise);
}
/** @private {promise.Promise<?>} */
this.parent_ = null;
/** @private {Array<!promise.Callback_>} */
this.callbacks_ = null;
/** @private {promise.Promise.State_} */
this.state_ = promise.Promise.State_.PENDING;
/** @private {boolean} */
this.handled_ = false;
/** @private {boolean} */
this.pendingNotifications_ = false;
/** @private {*} */
this.value_ = undefined;
try {
var self = this;
resolver(function(value) {
self.resolve_(promise.Promise.State_.FULFILLED, value);
}, function(reason) {
self.resolve_(promise.Promise.State_.REJECTED, reason);
});
} catch (ex) {
this.resolve_(promise.Promise.State_.REJECTED, ex);
}
};
promise.Thenable.addImplementation(promise.Promise);
/** @override */
promise.Promise.prototype.toString = function() {
return 'Promise::' + goog.getUid(this) +
' {[[PromiseStatus]]: "' + this.state_ + '"}';
};
/**
* @enum {string}
* @private
*/
promise.Promise.State_ = {
PENDING: "pending",
BLOCKED: "blocked",
REJECTED: "rejected",
FULFILLED: "fulfilled"
};
/**
* Resolves this promise. If the new value is itself a promise, this function
* will wait for it to be resolved before notifying the registered listeners.
* @param {promise.Promise.State_} newState The promise's new state.
* @param {*} newValue The promise's new value.
* @throws {TypeError} If {@code newValue === this}.
* @private
*/
promise.Promise.prototype.resolve_ = function(newState, newValue) {
if (promise.Promise.State_.PENDING !== this.state_) {
return;
}
if (newValue === this) {
// See promise a+, 2.3.1
// http://promises-aplus.github.io/promises-spec/#point-48
throw new TypeError('A promise may not resolve to itself');
}
this.parent_ = null;
this.state_ = promise.Promise.State_.BLOCKED;
if (promise.Thenable.isImplementation(newValue)) {
// 2.3.2
newValue = /** @type {!promise.Thenable} */(newValue);
newValue.then(
this.unblockAndResolve_.bind(this, promise.Promise.State_.FULFILLED),
this.unblockAndResolve_.bind(this, promise.Promise.State_.REJECTED));
return;
} else if (goog.isObject(newValue)) {
// 2.3.3
try {
// 2.3.3.1
var then = newValue['then'];
} catch (e) {
// 2.3.3.2
this.state_ = promise.Promise.State_.REJECTED;
this.value_ = e;
this.scheduleNotifications_();
return;
}
// NB: goog.isFunction is loose and will accept instanceof Function.
if (typeof then === 'function') {
// 2.3.3.3
this.invokeThen_(newValue, then);
return;
}
}
if (newState === promise.Promise.State_.REJECTED &&
promise.isError_(newValue) && newValue.stack && this.stack_) {
newValue.stack += '\nFrom: ' + (this.stack_.stack || this.stack_);
}
// 2.3.3.4 and 2.3.4
this.state_ = newState;
this.value_ = newValue;
this.scheduleNotifications_();
};
/**
* Invokes a thenable's "then" method according to 2.3.3.3 of the promise
* A+ spec.
* @param {!Object} x The thenable object.
* @param {!Function} then The "then" function to invoke.
* @private
*/
promise.Promise.prototype.invokeThen_ = function(x, then) {
var called = false;
var self = this;
var resolvePromise = function(value) {
if (!called) { // 2.3.3.3.3
called = true;
// 2.3.3.3.1
self.unblockAndResolve_(promise.Promise.State_.FULFILLED, value);
}
};
var rejectPromise = function(reason) {
if (!called) { // 2.3.3.3.3
called = true;
// 2.3.3.3.2
self.unblockAndResolve_(promise.Promise.State_.REJECTED, reason);
}
};
try {
// 2.3.3.3
then.call(x, resolvePromise, rejectPromise);
} catch (e) {
// 2.3.3.3.4.2
rejectPromise(e);
}
};
/**
* @param {promise.Promise.State_} newState The promise's new state.
* @param {*} newValue The promise's new value.
* @private
*/
promise.Promise.prototype.unblockAndResolve_ = function(newState, newValue) {
if (this.state_ === promise.Promise.State_.BLOCKED) {
this.state_ = promise.Promise.State_.PENDING;
this.resolve_(newState, newValue);
}
};
/**
* @private
*/
promise.Promise.prototype.scheduleNotifications_ = function() {
if (!this.pendingNotifications_) {
this.pendingNotifications_ = true;
this.flow_.suspend_();
var activeFrame;
if (!this.handled_ &&
this.state_ === promise.Promise.State_.REJECTED &&
!(this.value_ instanceof promise.CancellationError)) {
activeFrame = this.flow_.getActiveFrame_();
activeFrame.pendingRejection = true;
}
if (this.callbacks_ && this.callbacks_.length) {
activeFrame = this.flow_.getSchedulingFrame_();
var self = this;
goog.array.forEach(this.callbacks_, function(callback) {
if (!callback.frame_.getParent()) {
activeFrame.addChild(callback.frame_);
}
});
}
goog.async.run(goog.bind(this.notifyAll_, this, activeFrame));
}
};
/**
* Notifies all of the listeners registered with this promise that its state
* has changed.
* @param {promise.Frame_} frame The active frame from when this round of
* notifications were scheduled.
* @private
*/
promise.Promise.prototype.notifyAll_ = function(frame) {
this.flow_.resume_();
this.pendingNotifications_ = false;
if (!this.handled_ &&
this.state_ === promise.Promise.State_.REJECTED &&
!(this.value_ instanceof promise.CancellationError)) {
this.flow_.abortFrame_(this.value_, frame);
}
if (this.callbacks_) {
var callbacks = this.callbacks_;
this.callbacks_ = null;
goog.array.forEach(callbacks, this.notify_, this);
}
};
/**
* Notifies a single callback of this promise's change ins tate.
* @param {promise.Callback_} callback The callback to notify.
* @private
*/
promise.Promise.prototype.notify_ = function(callback) {
callback.notify(this.state_, this.value_);
};
/** @override */
promise.Promise.prototype.cancel = function(opt_reason) {
if (!this.isPending()) {
return;
}
if (this.parent_) {
this.parent_.cancel(opt_reason);
} else {
this.resolve_(
promise.Promise.State_.REJECTED,
promise.CancellationError.wrap(opt_reason));
}
};
/** @override */
promise.Promise.prototype.isPending = function() {
return this.state_ === promise.Promise.State_.PENDING;
};
/** @override */
promise.Promise.prototype.then = function(opt_callback, opt_errback) {
return this.addCallback_(
opt_callback, opt_errback, 'then', promise.Promise.prototype.then);
};
/** @override */
promise.Promise.prototype.thenCatch = function(errback) {
return this.addCallback_(
null, errback, 'thenCatch', promise.Promise.prototype.thenCatch);
};
/** @override */
promise.Promise.prototype.thenFinally = function(callback) {
var error;
var mustThrow = false;
return this.then(function() {
return callback();
}, function(err) {
error = err;
mustThrow = true;
return callback();
}).then(function() {
if (mustThrow) {
throw error;
}
});
};
/**
* Registers a new callback with this promise
* @param {(function(T): (R|IThenable<R>)|null|undefined)} callback The
* fulfillment callback.
* @param {(function(*): (R|IThenable<R>)|null|undefined)} errback The
* rejection callback.
* @param {string} name The callback name.
* @param {!Function} fn The function to use as the top of the stack when
* recording the callback's creation point.
* @return {!promise.Promise<R>} A new promise which will be resolved with the
* esult of the invoked callback.
* @template R
* @private
*/
promise.Promise.prototype.addCallback_ = function(callback, errback, name, fn) {
if (!goog.isFunction(callback) && !goog.isFunction(errback)) {
return this;
}
this.handled_ = true;
var cb = new promise.Callback_(this, callback, errback, name, fn);
if (!this.callbacks_) {
this.callbacks_ = [];
}
this.callbacks_.push(cb);
if (this.state_ !== promise.Promise.State_.PENDING &&
this.state_ !== promise.Promise.State_.BLOCKED) {
this.flow_.getSchedulingFrame_().addChild(cb.frame_);
this.scheduleNotifications_();
}
return cb.promise;
};
/**
* Represents a value that will be resolved at some point in the future. This
* class represents the protected "producer" half of a Promise - each Deferred
* has a {@code promise} property that may be returned to consumers for
* registering callbacks, reserving the ability to resolve the deferred to the
* producer.
*
* <p>If this Deferred is rejected and there are no listeners registered before
* the next turn of the event loop, the rejection will be passed to the
* {@link promise.ControlFlow} as an unhandled failure.
*
* @param {promise.ControlFlow=} opt_flow The control flow
* this instance was created under. This should only be provided during
* unit tests.
* @constructor
* @implements {promise.Thenable<T>}
* @template T
*/
promise.Deferred = function(opt_flow) {
var fulfill, reject;
/** @type {!promise.Promise<T>} */
this.promise = new promise.Promise(function(f, r) {
fulfill = f;
reject = r;
}, opt_flow);
var self = this;
var checkNotSelf = function(value) {
if (value === self) {
throw new TypeError('May not resolve a Deferred with itself');
}
};
/**
* Resolves this deferred with the given value. It is safe to call this as a
* normal function (with no bound "this").
* @param {(T|IThenable<T>|Thenable)=} opt_value The fulfilled value.
*/
this.fulfill = function(opt_value) {
checkNotSelf(opt_value);
fulfill(opt_value);
};
/**
* Rejects this promise with the given reason. It is safe to call this as a
* normal function (with no bound "this").
* @param {*=} opt_reason The rejection reason.
*/
this.reject = function(opt_reason) {
checkNotSelf(opt_reason);
reject(opt_reason);
};
};
promise.Thenable.addImplementation(promise.Deferred);
/** @override */
promise.Deferred.prototype.isPending = function() {
return this.promise.isPending();
};
/** @override */
promise.Deferred.prototype.cancel = function(opt_reason) {
this.promise.cancel(opt_reason);
};
/**
* @override
* @deprecated Use {@code then} from the promise property directly.
*/
promise.Deferred.prototype.then = function(opt_cb, opt_eb) {
return this.promise.then(opt_cb, opt_eb);
};
/**
* @override
* @deprecated Use {@code thenCatch} from the promise property directly.
*/
promise.Deferred.prototype.thenCatch = function(opt_eb) {
return this.promise.thenCatch(opt_eb);
};
/**
* @override
* @deprecated Use {@code thenFinally} from the promise property directly.
*/
promise.Deferred.prototype.thenFinally = function(opt_cb) {
return this.promise.thenFinally(opt_cb);
};
/**
* Tests if a value is an Error-like object. This is more than an straight
* instanceof check since the value may originate from another context.
* @param {*} value The value to test.
* @return {boolean} Whether the value is an error.
* @private
*/
promise.isError_ = function(value) {
return value instanceof Error ||
goog.isObject(value) &&
(goog.isString(value.message) ||
// A special test for goog.testing.JsUnitException.
value.isJsUnitException);
};
/**
* Determines whether a {@code value} should be treated as a promise.
* Any object whose "then" property is a function will be considered a promise.
*
* @param {*} value The value to test.
* @return {boolean} Whether the value is a promise.
*/
promise.isPromise = function(value) {
return !!value && goog.isObject(value) &&
// Use array notation so the Closure compiler does not obfuscate away our
// contract. Use typeof rather than goog.isFunction because
// goog.isFunction accepts instanceof Function, which the promise spec
// does not.
typeof value['then'] === 'function';
};
/**
* Creates a promise that will be resolved at a set time in the future.
* @param {number} ms The amount of time, in milliseconds, to wait before
* resolving the promise.
* @return {!promise.Promise} The promise.
*/
promise.delayed = function(ms) {
var key;
return new promise.Promise(function(fulfill) {
key = setTimeout(function() {
key = null;
fulfill();
}, ms);
}).thenCatch(function(e) {
clearTimeout(key);
key = null;
throw e;
});
};
/**
* Creates a new deferred object.
* @return {!promise.Deferred<T>} The new deferred object.
* @template T
*/
promise.defer = function() {
return new promise.Deferred();
};
/**
* Creates a promise that has been resolved with the given value.
* @param {T=} opt_value The resolved value.
* @return {!promise.Promise<T>} The resolved promise.
* @template T
*/
promise.fulfilled = function(opt_value) {
if (opt_value instanceof promise.Promise) {
return opt_value;
}
return new promise.Promise(function(fulfill) {
fulfill(opt_value);
});
};
/**
* Creates a promise that has been rejected with the given reason.
* @param {*=} opt_reason The rejection reason; may be any value, but is
* usually an Error or a string.
* @return {!promise.Promise<T>} The rejected promise.
* @template T
*/
promise.rejected = function(opt_reason) {
if (opt_reason instanceof promise.Promise) {
return opt_reason;
}
return new promise.Promise(function(_, reject) {
reject(opt_reason);
});
};
/**
* Wraps a function that is assumed to be a node-style callback as its final
* argument. This callback takes two arguments: an error value (which will be
* null if the call succeeded), and the success value as the second argument.
* If the call fails, the returned promise will be rejected, otherwise it will
* be resolved with the result.
* @param {!Function} fn The function to wrap.
* @param {...?} var_args The arguments to apply to the function, excluding the
* final callback.
* @return {!promise.Promise} A promise that will be resolved with the
* result of the provided function's callback.
*/
promise.checkedNodeCall = function(fn, var_args) {
var args = goog.array.slice(arguments, 1);
return new promise.Promise(function(fulfill, reject) {
try {
args.push(function(error, value) {
error ? reject(error) : fulfill(value);
});
fn.apply(undefined, args);
} catch (ex) {
reject(ex);
}
});
};
/**
* Registers an observer on a promised {@code value}, returning a new promise
* that will be resolved when the value is. If {@code value} is not a promise,
* then the return promise will be immediately resolved.
* @param {*} value The value to observe.
* @param {Function=} opt_callback The function to call when the value is
* resolved successfully.
* @param {Function=} opt_errback The function to call when the value is
* rejected.
* @return {!promise.Promise} A new promise.
*/
promise.when = function(value, opt_callback, opt_errback) {
if (promise.Thenable.isImplementation(value)) {
return value.then(opt_callback, opt_errback);
}
return new promise.Promise(function(fulfill, reject) {
promise.asap(value, fulfill, reject);
}).then(opt_callback, opt_errback);
};
/**
* Invokes the appropriate callback function as soon as a promised
* {@code value} is resolved. This function is similar to
* {@link promise.when}, except it does not return a new promise.
* @param {*} value The value to observe.
* @param {Function} callback The function to call when the value is
* resolved successfully.
* @param {Function=} opt_errback The function to call when the value is
* rejected.
*/
promise.asap = function(value, callback, opt_errback) {
if (promise.isPromise(value)) {
value.then(callback, opt_errback);
// Maybe a Dojo-like deferred object?
} else if (!!value && goog.isObject(value) &&
goog.isFunction(value.addCallbacks)) {
value.addCallbacks(callback, opt_errback);
// A raw value, return a resolved promise.
} else if (callback) {
callback(value);
}
};
/**
* Given an array of promises, will return a promise that will be fulfilled
* with the fulfillment values of the input array's values. If any of the
* input array's promises are rejected, the returned promise will be rejected
* with the same reason.
*
* @param {!Array<(T|!promise.Promise<T>)>} arr An array of
* promises to wait on.
* @return {!promise.Promise<!Array<T>>} A promise that is
* fulfilled with an array containing the fulfilled values of the
* input array, or rejected with the same reason as the first
* rejected value.
* @template T
*/
promise.all = function(arr) {
return new promise.Promise(function(fulfill, reject) {
var n = arr.length;
var values = [];
if (!n) {
fulfill(values);
return;
}
var toFulfill = n;
var onFulfilled = function(index, value) {
values[index] = value;
toFulfill--;
if (toFulfill == 0) {
fulfill(values);
}
};
for (var i = 0; i < n; ++i) {
promise.asap(arr[i], goog.partial(onFulfilled, i), reject);
}
});
};
/**
* Calls a function for each element in an array and inserts the result into a
* new array, which is used as the fulfillment value of the promise returned
* by this function.
*
* <p>If the return value of the mapping function is a promise, this function
* will wait for it to be fulfilled before inserting it into the new array.
*
* <p>If the mapping function throws or returns a rejected promise, the
* promise returned by this function will be rejected with the same reason.
* Only the first failure will be reported; all subsequent errors will be
* silently ignored.
*
* @param {!(Array<TYPE>|promise.Promise<!Array<TYPE>>)} arr The
* array to iterator over, or a promise that will resolve to said array.
* @param {function(this: SELF, TYPE, number, !Array<TYPE>): ?} fn The
* function to call for each element in the array. This function should
* expect three arguments (the element, the index, and the array itself.
* @param {SELF=} opt_self The object to be used as the value of 'this' within
* {@code fn}.
* @template TYPE, SELF
*/
promise.map = function(arr, fn, opt_self) {
return promise.fulfilled(arr).then(function(arr) {
goog.asserts.assertNumber(arr.length, 'not an array like value');
return new promise.Promise(function(fulfill, reject) {
var n = arr.length;
var values = new Array(n);
(function processNext(i) {
for (; i < n; i++) {
if (i in arr) {