This repository has been archived by the owner on Dec 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Promise.ts
1491 lines (1289 loc) · 37.2 KB
/
Promise.ts
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
/*!
* @author electricessence / https://github.com/electricessence/
* Licensing: MIT
* Although most of the following code is written from scratch, it is
* heavily influenced by Q (https://github.com/kriskowal/q) and uses some of Q's spec.
*/
/*
* Resources:
* https://promisesaplus.com/
* https://github.com/kriskowal/q
*/
import Type from "../Types";
import {deferImmediate} from "../Threading/deferImmediate";
import {DisposableBase} from "../Disposable/DisposableBase";
import {InvalidOperationException} from "../Exceptions/InvalidOperationException";
import {ArgumentException} from "../Exceptions/ArgumentException";
import {ArgumentNullException} from "../Exceptions/ArgumentNullException";
import {ObjectPool} from "../Disposable/ObjectPool";
import {Set} from "../Collections/Set";
import {defer} from "../Threading/defer";
import {ObjectDisposedException} from "../Disposable/ObjectDisposedException";
import __extendsImport from "../../extends";
import {Closure, Selector} from "../FunctionTypes";
//noinspection JSUnusedLocalSymbols
const __extends = __extendsImport;
const VOID0:any = void 0, NULL:any = null, PROMISE = "Promise", PROMISE_STATE = PROMISE + "State",
THEN = "then", TARGET = "target";
function isPromise<T>(value:any):value is PromiseLike<T>
{
return Type.hasMemberOfType(value, THEN, Type.FUNCTION);
}
export type Resolver = Selector<TSDNPromise.Resolution<any>,any> | null | undefined;
function resolve<T>(
value:TSDNPromise.Resolution<T>, resolver:Resolver,
promiseFactory:(v:any) => PromiseBase<any>):PromiseBase<any>
{
let nextValue = resolver
? resolver(value)
: value;
return nextValue && isPromise(nextValue)
? TSDNPromise.wrap(nextValue)
: promiseFactory(nextValue);
}
function handleResolution(
p:TSDNPromise<any> | null | undefined,
value:TSDNPromise.Resolution<any>,
resolver?:Resolver):any
{
try
{
let v = resolver ? resolver(value) : value;
if(p)
{ //noinspection JSIgnoredPromiseFromCall
p.resolve(v);
}
return null;
}
catch(ex)
{
if(p)
{ //noinspection JSIgnoredPromiseFromCall
p.reject(ex);
}
return ex;
}
}
function handleResolutionMethods(
targetFulfill:TSDNPromise.Fulfill<any, any> | null | undefined,
targetReject:TSDNPromise.Reject<any> | null | undefined,
value:TSDNPromise.Resolution<any>,
resolver?:Resolver | null | undefined):void
{
try
{
let v = resolver ? resolver(value) : value;
if(targetFulfill) targetFulfill(v);
}
catch(ex)
{ if(targetReject) targetReject(ex); }
}
function handleDispatch<T, TFulfilled = T, TRejected = never>(
p:PromiseLike<T>,
onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null,
onRejected?:TSDNPromise.Reject<TRejected> | null):void
{
// noinspection SuspiciousInstanceOfGuard
if(p instanceof PromiseBase)
{
p.doneNow(onFulfilled, onRejected);
}
else
{
p.then(<any>onFulfilled, onRejected);
}
}
function handleSyncIfPossible<T, TFulfilled = T, TRejected = never>(
p:PromiseLike<T>,
onFulfilled:TSDNPromise.Fulfill<T, TFulfilled>,
onRejected?:TSDNPromise.Reject<TRejected>):PromiseLike<TFulfilled | TRejected>
{
// noinspection SuspiciousInstanceOfGuard
if(p instanceof PromiseBase)
return p.thenSynchronous(onFulfilled, onRejected);
else
return p.then(onFulfilled, onRejected);
}
function newODE()
{
return new ObjectDisposedException("TSDNPromise", "An underlying promise-result was disposed.");
}
export class PromiseState<T>
extends DisposableBase
{
constructor(
protected _state:TSDNPromise.State,
protected _result?:T,
protected _error?:any)
{
super(PROMISE_STATE);
}
protected _onDispose():void
{
this._state = VOID0;
this._result = VOID0;
this._error = VOID0;
}
protected getState():TSDNPromise.State
{
return this._state;
}
get state():TSDNPromise.State
{
return this._state;
}
get isPending():boolean
{
return this.getState()===TSDNPromise.State.Pending;
}
get isSettled():boolean
{
return this.getState()!=TSDNPromise.State.Pending; // Will also include undefined==0 aka disposed!=resolved.
}
get isFulfilled():boolean
{
return this.getState()===TSDNPromise.State.Fulfilled;
}
get isRejected():boolean
{
return this.getState()===TSDNPromise.State.Rejected;
}
/*
* Providing overrides allows for special defer or lazy sub classes.
*/
protected getResult():T | undefined
{
return this._result;
}
get result():T | undefined
{
this.throwIfDisposed();
return this.getResult();
}
protected getError():any
{
return this._error;
}
get error():any
{
this.throwIfDisposed();
return this.getError();
}
}
export abstract class PromiseBase<T>
extends PromiseState<T>
implements PromiseLike<T>// , Promise<T>
{
//readonly [Symbol.toStringTag]: "Promise";
protected constructor()
{
super(TSDNPromise.State.Pending);
// @ts-ignore
this._disposableObjectName = PROMISE;
}
/**
* .doneNow is provided as a non-standard means that synchronously resolves as the end of a promise chain.
* As stated by promisejs.org: 'then' is to 'done' as 'map' is to 'forEach'.
* It is the underlying method by which propagation occurs.
* @param onFulfilled
* @param onRejected
*/
abstract doneNow(
onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null,
onRejected?:TSDNPromise.Reject<any> | null):void;
/**
* Calls the respective handlers once the promise is resolved.
* @param onFulfilled
* @param onRejected
*/
abstract thenSynchronous<TFulfilled = T, TRejected = never>(
onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null,
onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected>;
/**
* Same as 'thenSynchronous' but does not return the result. Returns the current promise instead.
* You may not need an additional promise result, and this will not create a new one.
* @param onFulfilled
* @param onRejected
*/
thenThis(
onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null,
onRejected?:TSDNPromise.Reject<any> | null):this
{
this.doneNow(onFulfilled, onRejected);
return this;
}
/**
* Standard .then method that defers execution until resolved.
* @param onFulfilled
* @param onRejected
* @returns {TSDNPromise}
*/
then<TFulfilled = T, TRejected = never>(
onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null,
onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected>
{
this.throwIfDisposed();
return new TSDNPromise<TFulfilled | TRejected>((resolve, reject) => {
this.doneNow(
result =>
handleResolutionMethods(resolve, reject, result, onFulfilled),
error =>
onRejected
? handleResolutionMethods(resolve, reject, error, onRejected)
: reject(error)
);
});
}
/**
* Same as .then but doesn't trap errors. Exceptions may end up being fatal.
* @param onFulfilled
* @param onRejected
* @returns {TSDNPromise}
*/
thenAllowFatal<TFulfilled = T, TRejected = never>(
onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null,
onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected>
{
this.throwIfDisposed();
return new TSDNPromise<TFulfilled | TRejected>((resolve, reject) => {
this.doneNow(
result =>
resolve(<any>(onFulfilled ? onFulfilled(result) : result)),
error =>
reject(onRejected ? onRejected(error) : error)
);
});
}
/**
* .done is provided as a non-standard means that maps to similar functionality in other promise libraries.
* As stated by promisejs.org: 'then' is to 'done' as 'map' is to 'forEach'.
* @param onFulfilled
* @param onRejected
*/
done(
onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null,
onRejected?:TSDNPromise.Reject<any> | null):void
{
defer(() => this.doneNow(onFulfilled, onRejected));
}
/**
* Will yield for a number of milliseconds from the time called before continuing.
* @param milliseconds
* @returns A promise that yields to the current execution and executes after a delay.
*/
delayFromNow(milliseconds:number = 0):PromiseBase<T>
{
this.throwIfDisposed();
return new TSDNPromise<T>(
(resolve, reject) => {
defer(() => {
this.doneNow(
v => resolve(v),
e => reject(e));
}, milliseconds)
},
true // Since the resolve/reject is deferred.
);
}
/**
* Will yield for a number of milliseconds from after this promise resolves.
* If the promise is already resolved, the delay will start from now.
* @param milliseconds
* @returns A promise that yields to the current execution and executes after a delay.
*/
delayAfterResolve(milliseconds:number = 0):PromiseBase<T>
{
this.throwIfDisposed();
if(this.isSettled) return this.delayFromNow(milliseconds);
return new TSDNPromise<T>(
(resolve, reject) => {
this.doneNow(
v => defer(() => resolve(v), milliseconds),
e => defer(() => reject(e), milliseconds))
},
true // Since the resolve/reject is deferred.
);
}
/**
* Shortcut for trapping a rejection.
* @param onRejected
* @returns {PromiseBase<TResult>}
*/
'catch'<TResult = never>(onRejected:TSDNPromise.Reject<TResult>):PromiseBase<T | TResult>
{
return this.then(VOID0, onRejected)
}
/**
* Shortcut for trapping a rejection but will allow exceptions to propagate within the onRejected handler.
* @param onRejected
* @returns {PromiseBase<TResult>}
*/
catchAllowFatal<TResult = never>(onRejected:TSDNPromise.Reject<TResult>):PromiseBase<T | TResult>
{
return this.thenAllowFatal(VOID0, onRejected)
}
/**
* Shortcut to for handling either resolve or reject.
* @param fin
* @returns {PromiseBase<TResult>}
*/
'finally'<TResult = never>(fin:() => TSDNPromise.Resolution<TResult>):PromiseBase<TResult>
{
return this.then(fin, fin);
}
/**
* Shortcut to for handling either resolve or reject but will allow exceptions to propagate within the handler.
* @param fin
* @returns {PromiseBase<TResult>}
*/
finallyAllowFatal<TResult = never>(fin:() => TSDNPromise.Resolution<TResult>):PromiseBase<TResult>
{
return this.thenAllowFatal(fin, fin);
}
/**
* Shortcut to for handling either resolve or reject. Returns the current promise instead.
* You may not need an additional promise result, and this will not create a new one.
* @param fin
* @param synchronous
* @returns {PromiseBase}
*/
finallyThis(fin:Closure, synchronous?:boolean):this
{
const f:Closure = synchronous ? fin : () => deferImmediate(fin);
this.doneNow(f, f);
return this;
}
}
export abstract class Resolvable<T>
extends PromiseBase<T>
{
doneNow(
onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null,
onRejected?:TSDNPromise.Reject<any> | null):void
{
this.throwIfDisposed();
switch(this.state)
{
case TSDNPromise.State.Fulfilled:
if(onFulfilled) onFulfilled(this._result!);
break;
case TSDNPromise.State.Rejected:
if(onRejected) onRejected(this._error);
break;
}
}
thenSynchronous<TFulfilled = T, TRejected = never>(
onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null,
onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected>
{
this.throwIfDisposed();
try
{
switch(this.state)
{
case TSDNPromise.State.Fulfilled:
return onFulfilled
? resolve(this._result, onFulfilled, TSDNPromise.resolve)
: <any>this; // Provided for catch cases.
case TSDNPromise.State.Rejected:
return onRejected
? resolve(this._error, onRejected, TSDNPromise.resolve)
: <any>this;
}
}
catch(ex)
{
return new Rejected<any>(ex);
}
throw new Error("Invalid state for a resolved promise.");
}
}
/**
* The simplest usable version of a promise which returns synchronously the resolved state provided.
*/
export abstract class Resolved<T>
extends Resolvable<T>
{
protected constructor(state:TSDNPromise.State, result:T, error?:any)
{
super();
this._result = result;
this._error = error;
this._state = state;
}
}
/**
* A fulfilled Resolved<T>. Provided for readability.
*/
export class Fulfilled<T>
extends Resolved<T>
{
constructor(value:T)
{
super(TSDNPromise.State.Fulfilled, value);
}
}
/**
* A rejected Resolved<T>. Provided for readability.
*/
export class Rejected<T>
extends Resolved<T>
{
constructor(error:any)
{
super(TSDNPromise.State.Rejected, VOID0, error);
}
}
/**
* Provided as a means for extending the interface of other PromiseLike<T> objects.
*/
class PromiseWrapper<T>
extends Resolvable<T>
{
constructor(private _target:PromiseLike<T>)
{
super();
if(!_target)
throw new ArgumentNullException(TARGET);
if(!isPromise(_target))
throw new ArgumentException(TARGET, "Must be a promise-like object.");
_target.then(
(v:T) => {
this._state = TSDNPromise.State.Fulfilled;
this._result = v;
this._error = VOID0;
this._target = VOID0;
},
e => {
this._state = TSDNPromise.State.Rejected;
this._error = e;
this._target = VOID0;
})
}
thenSynchronous<TFulfilled = T, TRejected = never>(
onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null,
onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected>
{
this.throwIfDisposed();
let t = this._target;
if(!t) return super.thenSynchronous(onFulfilled, onRejected);
return new TSDNPromise<TFulfilled | TRejected>((resolve, reject) => {
handleDispatch(t,
result => handleResolutionMethods(resolve, reject, result, onFulfilled),
error => onRejected
? handleResolutionMethods(resolve, null, error, onRejected)
: reject(error)
);
}, true);
}
doneNow(
onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null,
onRejected?:TSDNPromise.Reject<any> | null):void
{
this.throwIfDisposed();
let t = this._target;
if(t)
handleDispatch(t, onFulfilled, onRejected);
else
super.doneNow(onFulfilled, onRejected);
}
protected _onDispose():void
{
super._onDispose();
this._target = VOID0;
}
}
/**
* This promise class that facilitates pending resolution.
*/
export class TSDNPromise<T>
extends Resolvable<T>
{
private _waiting:IPromiseCallbacks<any>[] | null | undefined;
/*
* A note about deferring:
* The caller can set resolveImmediate to true if they intend to initialize code that will end up being deferred itself.
* This eliminates the extra defer that will occur internally.
* But for the most part, resolveImmediate = false (the default) will ensure the constructor will not block.
*
* resolveUsing allows for the same ability but does not defer by default: allowing the caller to take on the work load.
* If calling resolve or reject and a deferred response is desired, then use deferImmediate with a closure to do so.
*/
constructor(
resolver?:TSDNPromise.Executor<T>, forceSynchronous:boolean = false)
{
super();
if(resolver) this.resolveUsing(resolver, forceSynchronous);
}
thenSynchronous<TFulfilled = T, TRejected = never>(
onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null,
onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected>
{
this.throwIfDisposed();
// Already fulfilled?
if(this._state) return super.thenSynchronous(onFulfilled, onRejected);
const p = new TSDNPromise<TFulfilled | TRejected>();
(this._waiting || (this._waiting = []))
.push(pools.PromiseCallbacks.init(onFulfilled, onRejected, p));
return p;
}
doneNow(
onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null,
onRejected?:TSDNPromise.Reject<any> | null):void
{
this.throwIfDisposed();
// Already fulfilled?
if(this._state)
return super.doneNow(onFulfilled, onRejected);
(this._waiting || (this._waiting = []))
.push(pools.PromiseCallbacks.init(onFulfilled, onRejected));
}
protected _onDispose()
{
super._onDispose();
this._resolvedCalled = VOID0;
}
// Protects against double calling.
protected _resolvedCalled:boolean | undefined;
resolveUsing(
resolver:TSDNPromise.Executor<T>,
forceSynchronous:boolean = false):void
{
if(!resolver)
throw new ArgumentNullException("resolver");
if(this._resolvedCalled)
throw new InvalidOperationException(".resolve() already called.");
if(this.state)
throw new InvalidOperationException("Already resolved: " + TSDNPromise.State[this.state]);
this._resolvedCalled = true;
let state = 0;
const rejectHandler = (reason:any) => {
if(state)
{
// Someone else's promise handling down stream could double call this. :\
console.warn(state== -1
? "Rejection called multiple times"
: "Rejection called after fulfilled.");
}
else
{
state = -1;
this._resolvedCalled = false;
this.reject(reason);
}
};
const fulfillHandler = (v:any) => {
if(state)
{
// Someone else's promise handling down stream could double call this. :\
console.warn(state==1
? "Fulfill called multiple times"
: "Fulfill called after rejection.");
}
else
{
state = 1;
this._resolvedCalled = false;
this.resolve(v);
}
};
// There are some performance edge cases where there caller is not blocking upstream and does not need to defer.
if(forceSynchronous)
resolver(fulfillHandler, rejectHandler);
else
deferImmediate(() => resolver(fulfillHandler, rejectHandler));
}
private _emitDisposalRejection(p:PromiseBase<any>):boolean
{
const d = p.wasDisposed;
if(d) this._rejectInternal(newODE());
return d;
}
private _resolveInternal(result?:T | PromiseLike<T>):void
{
if(this.wasDisposed) return;
// Note: Avoid recursion if possible.
// Check ahead of time for resolution and resolve appropriately
// noinspection SuspiciousInstanceOfGuard
while(result instanceof PromiseBase)
{
let r:PromiseBase<T> = <any>result;
if(this._emitDisposalRejection(r)) return;
switch(r.state)
{
case TSDNPromise.State.Pending:
r.doneNow(
v => this._resolveInternal(v),
e => this._rejectInternal(e)
);
return;
case TSDNPromise.State.Rejected:
this._rejectInternal(r.error);
return;
case TSDNPromise.State.Fulfilled:
result = r.result;
break;
}
}
if(isPromise(result))
{
result.then(
v => this._resolveInternal(v),
e => this._rejectInternal(e)
);
}
else
{
this._state = TSDNPromise.State.Fulfilled;
this._result = result;
this._error = VOID0;
const o = this._waiting;
if(o)
{
this._waiting = VOID0;
for(let c of o)
{
let {onFulfilled, promise} = c;
pools.PromiseCallbacks.recycle(c);
//let ex =
handleResolution(<any>promise, result, onFulfilled);
//if(!p && ex) console.error("Unhandled exception in onFulfilled:",ex);
}
o.length = 0;
}
}
}
private _rejectInternal(error:any):void
{
if(this.wasDisposed) return;
this._state = TSDNPromise.State.Rejected;
this._error = error;
const o = this._waiting;
if(o)
{
this._waiting = null; // null = finished. undefined = hasn't started.
for(let c of o)
{
let {onRejected, promise} = c;
pools.PromiseCallbacks.recycle(c);
if(onRejected)
{
//let ex =
handleResolution(promise, error, onRejected);
//if(!p && ex) console.error("Unhandled exception in onRejected:",ex);
}
else if(promise)
{ //noinspection JSIgnoredPromiseFromCall
promise.reject(error);
}
}
o.length = 0;
}
}
resolve(result?:T | PromiseLike<T>, throwIfSettled:boolean = false):void
{
this.throwIfDisposed();
if(<any>result==this)
throw new InvalidOperationException("Cannot resolve a promise as itself.");
if(this._state)
{
// Same value? Ignore...
if(!throwIfSettled || this._state==TSDNPromise.State.Fulfilled && this._result===result) return;
throw new InvalidOperationException("Changing the fulfilled state/value of a promise is not supported.");
}
if(this._resolvedCalled)
{
if(throwIfSettled)
throw new InvalidOperationException(".resolve() already called.");
return;
}
this._resolveInternal(result);
}
reject(error:any, throwIfSettled:boolean = false):void
{
this.throwIfDisposed();
if(this._state)
{
// Same value? Ignore...
if(!throwIfSettled || this._state==TSDNPromise.State.Rejected && this._error===error) return;
throw new InvalidOperationException("Changing the rejected state/value of a promise is not supported.");
}
if(this._resolvedCalled)
{
if(throwIfSettled)
throw new InvalidOperationException(".resolve() already called.");
return;
}
this._rejectInternal(error);
}
}
/**
* By providing an ArrayPromise we expose useful methods/shortcuts for dealing with array results.
*/
export class ArrayPromise<T>
extends TSDNPromise<T[]>
{
/**
* Simplifies the use of a map function on an array of results when the source is assured to be an array.
* @param transform
* @returns {PromiseBase<Array<any>>}
*/
map<U>(transform:(value:T) => U):ArrayPromise<U>
{
this.throwIfDisposed();
return new ArrayPromise<U>(resolve => {
this.doneNow(result => resolve(result.map(transform)));
}, true);
}
reduce(
reduction:(previousValue:T, currentValue:T, i?:number, array?:T[]) => T,
initialValue?:T):PromiseBase<T>
reduce<U>(
reduction:(previousValue:U, currentValue:T, i?:number, array?:T[]) => U,
initialValue:U):PromiseBase<U>
/**
* Simplifies the use of a reduce function on an array of results when the source is assured to be an array.
* @param reduction
* @param initialValue
* @returns {PromiseBase<any>}
*/
reduce<U>(
reduction:(previousValue:U, currentValue:T, i?:number, array?:T[]) => U,
initialValue?:U):PromiseBase<U>
{
return this
.thenSynchronous(result => result.reduce(reduction, <any>initialValue));
}
static fulfilled<T>(value:T[]):ArrayPromise<T>
{
return new ArrayPromise<T>(resolve => value, true);
}
}
const PROMISE_COLLECTION = "PromiseCollection";
/**
* A Promise collection exposes useful methods for handling a collection of promises and their results.
*/
export class PromiseCollection<T>
extends DisposableBase
{
private readonly _source:PromiseLike<T>[];
constructor(source:PromiseLike<T>[] | null | undefined)
{
super(PROMISE_COLLECTION);
this._source = source && source.slice() || [];
}
protected _onDispose()
{
super._onDispose();
this._source.length = 0;
(<any>this)._source = null;
}
/**
* Returns a copy of the source promises.
* @returns {PromiseLike<PromiseLike<any>>[]}
*/
get promises():PromiseLike<T>[]
{
this.throwIfDisposed();
return this._source.slice();
}
/**
* Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected.
* @returns {PromiseBase<any>}
*/
all():ArrayPromise<T>
{
this.throwIfDisposed();
return TSDNPromise.all(this._source);
}
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @returns {PromiseBase<any>} A new Promise.
*/
race():PromiseBase<T>
{
this.throwIfDisposed();
return TSDNPromise.race(this._source);
}
/**
* Returns a promise that is fulfilled with array of provided promises when all provided promises have resolved (fulfill or reject).
* Unlike .all this method waits for all rejections as well as fulfillment.
* @returns {PromiseBase<PromiseLike<any>[]>}
*/
waitAll():ArrayPromise<PromiseLike<T>>
{
this.throwIfDisposed();
return TSDNPromise.waitAll(this._source);
}
/**
* Waits for all the values to resolve and then applies a transform.
* @param transform
* @returns {PromiseBase<Array<any>>}
*/
map<U>(transform:(value:T) => U):ArrayPromise<U>
{
this.throwIfDisposed();
return new ArrayPromise<U>(resolve => {
this.all()
.doneNow(result => resolve(result.map(transform)));
}, true);
}
/**
* Applies a transform to each promise and defers the result.
* Unlike map, this doesn't wait for all promises to resolve, ultimately improving the async nature of the request.
* @param transform
* @returns {PromiseCollection<U>}
*/
pipe<U>(transform:(value:T) => U | PromiseLike<U>):PromiseCollection<U>
{
this.throwIfDisposed();
return new PromiseCollection<U>(
this._source.map(p => handleSyncIfPossible(p, transform))
);
}
reduce(
reduction:(previousValue:T, currentValue:T, i?:number, array?:PromiseLike<T>[]) => T,
initialValue?:T | PromiseLike<T>):PromiseBase<T>
reduce<U>(
reduction:(previousValue:U, currentValue:T, i?:number, array?:PromiseLike<T>[]) => U,
initialValue:U | PromiseLike<U>):PromiseBase<U>
/**
* Behaves like array reduce.
* Creates the promise chain necessary to produce the desired result.
* @param reduction
* @param initialValue
* @returns {PromiseBase<PromiseLike<any>>}
*/
reduce<U>(
reduction:(previousValue:U, currentValue:T, i?:number, array?:PromiseLike<T>[]) => U,
initialValue?:U | PromiseLike<U>):PromiseBase<U>
{
this.throwIfDisposed();
return TSDNPromise.wrap<U>(this._source
.reduce(
(
previous:PromiseLike<U>,