forked from Real-Serious-Games/C-Sharp-Promise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Promise_NonGeneric.cs
951 lines (816 loc) · 30.5 KB
/
Promise_NonGeneric.cs
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
using RSG.Promises;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RSG
{
/// <summary>
/// Implements a non-generic C# promise, this is a promise that simply resolves without delivering a value.
/// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
/// </summary>
public interface IPromise
{
/// <summary>
/// ID of the promise, useful for debugging.
/// </summary>
int Id { get; }
/// <summary>
/// Set the name of the promise, useful for debugging.
/// </summary>
IPromise WithName(string name);
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// onRejected is called on error.
/// </summary>
void Done(Action onResolved, Action<Exception> onRejected);
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// Adds a default error handler.
/// </summary>
void Done(Action onResolved);
/// <summary>
/// Complete the promise. Adds a default error handler.
/// </summary>
void Done();
/// <summary>
/// Handle errors for the promise.
/// </summary>
IPromise Catch(Action<Exception> onRejected);
/// <summary>
/// Add a resolved callback that chains a value promise (optionally converting to a different value type).
/// </summary>
IPromise<ConvertedT> Then<ConvertedT>(Func<IPromise<ConvertedT>> onResolved);
/// <summary>
/// Add a resolved callback that chains a non-value promise.
/// </summary>
IPromise Then(Func<IPromise> onResolved);
/// <summary>
/// Add a resolved callback.
/// </summary>
IPromise Then(Action onResolved);
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a value promise (optionally converting to a different value type).
/// </summary>
IPromise<ConvertedT> Then<ConvertedT>(Func<IPromise<ConvertedT>> onResolved, Action<Exception> onRejected);
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a non-value promise.
/// </summary>
IPromise Then(Func<IPromise> onResolved, Action<Exception> onRejected);
/// <summary>
/// Add a resolved callback and a rejected callback.
/// </summary>
IPromise Then(Action onResolved, Action<Exception> onRejected);
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
IPromise ThenAll(Func<IEnumerable<IPromise>> chain);
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// Converts to a non-value promise.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
IPromise<IEnumerable<ConvertedT>> ThenAll<ConvertedT>(Func<IEnumerable<IPromise<ConvertedT>>> chain);
/// <summary>
/// Chain a sequence of operations using promises.
/// Reutrn a collection of functions each of which starts an async operation and yields a promise.
/// Each function will be called and each promise resolved in turn.
/// The resulting promise is resolved after each promise is resolved in sequence.
/// </summary>
IPromise ThenSequence(Func<IEnumerable<Func<IPromise>>> chain);
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Returns a promise that resolves when the first of the promises has resolved.
/// </summary>
IPromise ThenRace(Func<IEnumerable<IPromise>> chain);
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Converts to a value promise.
/// Returns a promise that resolves when the first of the promises has resolved.
/// </summary>
IPromise<ConvertedT> ThenRace<ConvertedT>(Func<IEnumerable<IPromise<ConvertedT>>> chain);
/// <summary>
/// Add a finally callback.
/// Finally callbacks will always be called, even if any preceding promise is rejected, or encounters an error.
/// </summary>
IPromise Finally(Action onComplete);
/// <summary>
/// Add a finally callback that chains a non-value promise.
/// </summary>
IPromise Finally(Func<IPromise> onResolved);
/// <summary>
/// Add a finally callback.
/// Finally callbacks will always be called, even if any preceding promise is rejected, or encounters an error.
/// </summary>
IPromise<ConvertedT> Finally<ConvertedT>(Func<IPromise<ConvertedT>> onComplete);
}
/// <summary>
/// Interface for a promise that can be rejected or resolved.
/// </summary>
public interface IPendingPromise : IRejectable
{
/// <summary>
/// ID of the promise, useful for debugging.
/// </summary>
int Id { get; }
/// <summary>
/// Resolve the promise with a particular value.
/// </summary>
void Resolve();
}
/// <summary>
/// Used to list information of pending promises.
/// </summary>
public interface IPromiseInfo
{
/// <summary>
/// Id of the promise.
/// </summary>
int Id { get; }
/// <summary>
/// Human-readable name for the promise.
/// </summary>
string Name { get; }
}
/// <summary>
/// Arguments to the UnhandledError event.
/// </summary>
public class ExceptionEventArgs : EventArgs
{
internal ExceptionEventArgs(Exception exception)
{
// Argument.NotNull(() => exception);
this.Exception = exception;
}
public Exception Exception
{
get;
private set;
}
}
/// <summary>
/// Represents a handler invoked when the promise is rejected.
/// </summary>
public struct RejectHandler
{
/// <summary>
/// Callback fn.
/// </summary>
public Action<Exception> callback;
/// <summary>
/// The promise that is rejected when there is an error while invoking the handler.
/// </summary>
public IRejectable rejectable;
}
/// <summary>
/// Implements a non-generic C# promise, this is a promise that simply resolves without delivering a value.
/// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
/// </summary>
public class Promise : IPromise, IPendingPromise, IPromiseInfo
{
/// <summary>
/// Set to true to enable tracking of promises.
/// </summary>
public static bool EnablePromiseTracking = false;
/// <summary>
/// Event raised for unhandled errors.
/// For this to work you have to complete your promises with a call to Done().
/// </summary>
public static event EventHandler<ExceptionEventArgs> UnhandledException
{
add { unhandlerException += value; }
remove { unhandlerException -= value; }
}
private static EventHandler<ExceptionEventArgs> unhandlerException;
/// <summary>
/// Id for the next promise that is created.
/// </summary>
private static int nextPromiseId = 0;
/// <summary>
/// Information about pending promises.
/// </summary>
internal static HashSet<IPromiseInfo> pendingPromises = new HashSet<IPromiseInfo>();
/// <summary>
/// Information about pending promises, useful for debugging.
/// This is only populated when 'EnablePromiseTracking' is set to true.
/// </summary>
public static IEnumerable<IPromiseInfo> GetPendingPromises()
{
return pendingPromises;
}
/// <summary>
/// The exception when the promise is rejected.
/// </summary>
private Exception rejectionException;
/// <summary>
/// Error handlers.
/// </summary>
private List<RejectHandler> rejectHandlers;
/// <summary>
/// Represents a handler invoked when the promise is resolved.
/// </summary>
public struct ResolveHandler
{
/// <summary>
/// Callback fn.
/// </summary>
public Action callback;
/// <summary>
/// The promise that is rejected when there is an error while invoking the handler.
/// </summary>
public IRejectable rejectable;
}
/// <summary>
/// Completed handlers that accept no value.
/// </summary>
private List<ResolveHandler> resolveHandlers;
/// <summary>
/// ID of the promise, useful for debugging.
/// </summary>
public int Id { get; }
/// <summary>
/// Name of the promise, when set, useful for debugging.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Tracks the current state of the promise.
/// </summary>
public PromiseState CurState { get; private set; }
public Promise()
{
this.CurState = PromiseState.Pending;
this.Id = NextId();
if (EnablePromiseTracking)
{
pendingPromises.Add(this);
}
}
public Promise(Action<Action, Action<Exception>> resolver)
{
this.CurState = PromiseState.Pending;
this.Id = NextId();
if (EnablePromiseTracking)
{
pendingPromises.Add(this);
}
try
{
resolver(
// Resolve
() => Resolve(),
// Reject
ex => Reject(ex)
);
}
catch (Exception ex)
{
Reject(ex);
}
}
/// <summary>
/// Increments the ID counter and gives us the ID for the next promise.
/// </summary>
internal static int NextId()
{
return ++nextPromiseId;
}
/// <summary>
/// Add a rejection handler for this promise.
/// </summary>
private void AddRejectHandler(Action<Exception> onRejected, IRejectable rejectable)
{
if (rejectHandlers == null)
{
rejectHandlers = new List<RejectHandler>();
}
rejectHandlers.Add(new RejectHandler()
{
callback = onRejected,
rejectable = rejectable
});
}
/// <summary>
/// Add a resolve handler for this promise.
/// </summary>
private void AddResolveHandler(Action onResolved, IRejectable rejectable)
{
if (resolveHandlers == null)
{
resolveHandlers = new List<ResolveHandler>();
}
resolveHandlers.Add(new ResolveHandler()
{
callback = onResolved,
rejectable = rejectable
});
}
/// <summary>
/// Invoke a single error handler.
/// </summary>
private void InvokeRejectHandler(Action<Exception> callback, IRejectable rejectable, Exception value)
{
// Argument.NotNull(() => callback);
// Argument.NotNull(() => rejectable);
try
{
callback(value);
}
catch (Exception ex)
{
rejectable.Reject(ex);
}
}
/// <summary>
/// Invoke a single resolve handler.
/// </summary>
private void InvokeResolveHandler(Action callback, IRejectable rejectable)
{
// Argument.NotNull(() => callback);
// Argument.NotNull(() => rejectable);
try
{
callback();
}
catch (Exception ex)
{
rejectable.Reject(ex);
}
}
/// <summary>
/// Helper function clear out all handlers after resolution or rejection.
/// </summary>
private void ClearHandlers()
{
rejectHandlers = null;
resolveHandlers = null;
}
/// <summary>
/// Invoke all reject handlers.
/// </summary>
private void InvokeRejectHandlers(Exception ex)
{
// Argument.NotNull(() => ex);
if (rejectHandlers != null)
{
rejectHandlers.Each(handler => InvokeRejectHandler(handler.callback, handler.rejectable, ex));
}
ClearHandlers();
}
/// <summary>
/// Invoke all resolve handlers.
/// </summary>
private void InvokeResolveHandlers()
{
if (resolveHandlers != null)
{
resolveHandlers.Each(handler => InvokeResolveHandler(handler.callback, handler.rejectable));
}
ClearHandlers();
}
/// <summary>
/// Reject the promise with an exception.
/// </summary>
public void Reject(Exception ex)
{
// Argument.NotNull(() => ex);
if (CurState != PromiseState.Pending)
{
throw new ApplicationException("Attempt to reject a promise that is already in state: " + CurState + ", a promise can only be rejected when it is still in state: " + PromiseState.Pending);
}
rejectionException = ex;
CurState = PromiseState.Rejected;
if (EnablePromiseTracking)
{
pendingPromises.Remove(this);
}
InvokeRejectHandlers(ex);
}
/// <summary>
/// Resolve the promise with a particular value.
/// </summary>
public void Resolve()
{
if (CurState != PromiseState.Pending)
{
throw new ApplicationException("Attempt to resolve a promise that is already in state: " + CurState + ", a promise can only be resolved when it is still in state: " + PromiseState.Pending);
}
CurState = PromiseState.Resolved;
if (EnablePromiseTracking)
{
pendingPromises.Remove(this);
}
InvokeResolveHandlers();
}
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// onRejected is called on error.
/// </summary>
public void Done(Action onResolved, Action<Exception> onRejected)
{
Then(onResolved, onRejected)
.Catch(ex =>
Promise.PropagateUnhandledException(this, ex)
);
}
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// Adds a default error handler.
/// </summary>
public void Done(Action onResolved)
{
Then(onResolved)
.Catch(ex =>
Promise.PropagateUnhandledException(this, ex)
);
}
/// <summary>
/// Complete the promise. Adds a defualt error handler.
/// </summary>
public void Done()
{
Catch(ex => PropagateUnhandledException(this, ex));
}
/// <summary>
/// Set the name of the promise, useful for debugging.
/// </summary>
public IPromise WithName(string name)
{
this.Name = name;
return this;
}
/// <summary>
/// Handle errors for the promise.
/// </summary>
public IPromise Catch(Action<Exception> onRejected)
{
// Argument.NotNull(() => onRejected);
var resultPromise = new Promise();
resultPromise.WithName(Name);
Action resolveHandler = () => resultPromise.Resolve();
Action<Exception> rejectHandler = ex =>
{
try
{
onRejected(ex);
resultPromise.Resolve();
}
catch (Exception callbackException)
{
resultPromise.Reject(callbackException);
}
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
return resultPromise;
}
/// <summary>
/// Add a resolved callback that chains a value promise (optionally converting to a different value type).
/// </summary>
public IPromise<ConvertedT> Then<ConvertedT>(Func<IPromise<ConvertedT>> onResolved)
{
return Then(onResolved, null);
}
/// <summary>
/// Add a resolved callback that chains a non-value promise.
/// </summary>
public IPromise Then(Func<IPromise> onResolved)
{
return Then(onResolved, null);
}
/// <summary>
/// Add a resolved callback.
/// </summary>
public IPromise Then(Action onResolved)
{
return Then(onResolved, null);
}
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a value promise (optionally converting to a different value type).
/// </summary>
public IPromise<ConvertedT> Then<ConvertedT>(Func<IPromise<ConvertedT>> onResolved, Action<Exception> onRejected)
{
// This version of the function must supply an onResolved.
// Otherwise there is now way to get the converted value to pass to the resulting promise.
// Argument.NotNull(() => onResolved);
var resultPromise = new Promise<ConvertedT>();
resultPromise.WithName(Name);
Action resolveHandler = () =>
{
onResolved()
.Then(
// Should not be necessary to specify the arg type on the next line, but Unity (mono) has an internal compiler error otherwise.
(ConvertedT chainedValue) => resultPromise.Resolve(chainedValue),
ex => resultPromise.Reject(ex)
);
};
Action<Exception> rejectHandler = ex =>
{
if (onRejected != null)
{
onRejected(ex);
}
resultPromise.Reject(ex);
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
return resultPromise;
}
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a non-value promise.
/// </summary>
public IPromise Then(Func<IPromise> onResolved, Action<Exception> onRejected)
{
var resultPromise = new Promise();
resultPromise.WithName(Name);
Action resolveHandler = () =>
{
if (onResolved != null)
{
onResolved()
.Then(
() => resultPromise.Resolve(),
ex => resultPromise.Reject(ex)
);
}
else
{
resultPromise.Resolve();
}
};
Action<Exception> rejectHandler = ex =>
{
if (onRejected != null)
{
onRejected(ex);
}
resultPromise.Reject(ex);
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
return resultPromise;
}
/// <summary>
/// Add a resolved callback and a rejected callback.
/// </summary>
public IPromise Then(Action onResolved, Action<Exception> onRejected)
{
var resultPromise = new Promise();
resultPromise.WithName(Name);
Action resolveHandler = () =>
{
if (onResolved != null)
{
onResolved();
}
resultPromise.Resolve();
};
Action<Exception> rejectHandler = ex =>
{
if (onRejected != null)
{
onRejected(ex);
}
resultPromise.Reject(ex);
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
return resultPromise;
}
/// <summary>
/// Helper function to invoke or register resolve/reject handlers.
/// </summary>
private void ActionHandlers(IRejectable resultPromise, Action resolveHandler, Action<Exception> rejectHandler)
{
if (CurState == PromiseState.Resolved)
{
InvokeResolveHandler(resolveHandler, resultPromise);
}
else if (CurState == PromiseState.Rejected)
{
InvokeRejectHandler(rejectHandler, resultPromise, rejectionException);
}
else
{
AddResolveHandler(resolveHandler, resultPromise);
AddRejectHandler(rejectHandler, resultPromise);
}
}
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
public IPromise ThenAll(Func<IEnumerable<IPromise>> chain)
{
return Then(() => Promise.All(chain()));
}
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// Converts to a non-value promise.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
public IPromise<IEnumerable<ConvertedT>> ThenAll<ConvertedT>(Func<IEnumerable<IPromise<ConvertedT>>> chain)
{
return Then(() => Promise<ConvertedT>.All(chain()));
}
/// <summary>
/// Returns a promise that resolves when all of the promises in the enumerable argument have resolved.
/// Returns a promise of a collection of the resolved results.
/// </summary>
public static IPromise All(params IPromise[] promises)
{
return All((IEnumerable<IPromise>)promises); // Cast is required to force use of the other All function.
}
/// <summary>
/// Returns a promise that resolves when all of the promises in the enumerable argument have resolved.
/// Returns a promise of a collection of the resolved results.
/// </summary>
public static IPromise All(IEnumerable<IPromise> promises)
{
var promisesArray = promises.ToArray();
if (promisesArray.Length == 0)
{
return Promise.Resolved();
}
var remainingCount = promisesArray.Length;
var resultPromise = new Promise();
resultPromise.WithName("All");
promisesArray.Each((promise, index) =>
{
promise
.Catch(ex =>
{
if (resultPromise.CurState == PromiseState.Pending)
{
// If a promise errorred and the result promise is still pending, reject it.
resultPromise.Reject(ex);
}
})
.Then(() =>
{
--remainingCount;
if (remainingCount <= 0)
{
// This will never happen if any of the promises errorred.
resultPromise.Resolve();
}
})
.Done();
});
return resultPromise;
}
/// <summary>
/// Chain a sequence of operations using promises.
/// Reutrn a collection of functions each of which starts an async operation and yields a promise.
/// Each function will be called and each promise resolved in turn.
/// The resulting promise is resolved after each promise is resolved in sequence.
/// </summary>
public IPromise ThenSequence(Func<IEnumerable<Func<IPromise>>> chain)
{
return Then(() => Sequence(chain()));
}
/// <summary>
/// Chain a number of operations using promises.
/// Takes a number of functions each of which starts an async operation and yields a promise.
/// </summary>
public static IPromise Sequence(params Func<IPromise>[] fns)
{
return Sequence((IEnumerable<Func<IPromise>>)fns);
}
/// <summary>
/// Chain a sequence of operations using promises.
/// Takes a collection of functions each of which starts an async operation and yields a promise.
/// </summary>
public static IPromise Sequence(IEnumerable<Func<IPromise>> fns)
{
return fns.Aggregate(
Resolved(),
(prevPromise, fn) =>
{
return prevPromise.Then(() => fn());
}
);
}
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Returns a promise that resolves when the first of the promises has resolved.
/// </summary>
public IPromise ThenRace(Func<IEnumerable<IPromise>> chain)
{
return Then(() => Race(chain()));
}
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Converts to a value promise.
/// Returns a promise that resolves when the first of the promises has resolved.
/// </summary>
public IPromise<ConvertedT> ThenRace<ConvertedT>(Func<IEnumerable<IPromise<ConvertedT>>> chain)
{
return Then(() => Promise<ConvertedT>.Race(chain()));
}
/// <summary>
/// Returns a promise that resolves when the first of the promises in the enumerable argument have resolved.
/// Returns the value from the first promise that has resolved.
/// </summary>
public static IPromise Race(params IPromise[] promises)
{
return Race((IEnumerable<IPromise>)promises); // Cast is required to force use of the other function.
}
/// <summary>
/// Returns a promise that resolves when the first of the promises in the enumerable argument have resolved.
/// Returns the value from the first promise that has resolved.
/// </summary>
public static IPromise Race(IEnumerable<IPromise> promises)
{
var promisesArray = promises.ToArray();
if (promisesArray.Length == 0)
{
throw new ApplicationException("At least 1 input promise must be provided for Race");
}
var resultPromise = new Promise();
resultPromise.WithName("Race");
promisesArray.Each((promise, index) =>
{
promise
.Catch(ex =>
{
if (resultPromise.CurState == PromiseState.Pending)
{
// If a promise errorred and the result promise is still pending, reject it.
resultPromise.Reject(ex);
}
})
.Then(() =>
{
if (resultPromise.CurState == PromiseState.Pending)
{
resultPromise.Resolve();
}
})
.Done();
});
return resultPromise;
}
/// <summary>
/// Convert a simple value directly into a resolved promise.
/// </summary>
public static IPromise Resolved()
{
var promise = new Promise();
promise.Resolve();
return promise;
}
/// <summary>
/// Convert an exception directly into a rejected promise.
/// </summary>
public static IPromise Rejected(Exception ex)
{
// Argument.NotNull(() => ex);
var promise = new Promise();
promise.Reject(ex);
return promise;
}
public IPromise Finally(Action onComplete)
{
Promise promise = new Promise();
promise.WithName(Name);
this.Then(() => { promise.Resolve(); });
this.Catch((e) => { promise.Resolve(); });
return promise.Then(onComplete);
}
public IPromise Finally(Func<IPromise> onComplete)
{
Promise promise = new Promise();
promise.WithName(Name);
this.Then(() => { promise.Resolve(); });
this.Catch((e) => { promise.Resolve(); });
return promise.Then(onComplete);
}
public IPromise<ConvertedT> Finally<ConvertedT>(Func<IPromise<ConvertedT>> onComplete)
{
Promise promise = new Promise();
promise.WithName(Name);
this.Then(() => { promise.Resolve(); });
this.Catch((e) => { promise.Resolve(); });
return promise.Then(() => { return onComplete(); });
}
/// <summary>
/// Raises the UnhandledException event.
/// </summary>
internal static void PropagateUnhandledException(object sender, Exception ex)
{
if (unhandlerException != null)
{
unhandlerException(sender, new ExceptionEventArgs(ex));
}
}
}
}