/// <summary> /// Creates a promise that resolves when all given promises resolve or rejects as soon /// as any given promise rejects /// </summary> /// <param name="others">the inner promises</param> /// <returns>a promise that resolves when all given promises resolve or rejects as soon /// as any given promise rejects</returns> public static Promise WhenAnyFail(List <Promise> others) { Deferred outerDeferred = Deferred.Create(); int waitCount = others.Count; foreach (var promise in others) { promise.Finally((p) => { lock (outerDeferred) { if (p.Exception != null && outerDeferred.IsFulfilled == false) { outerDeferred.Resolve(); } var decrementResult = Interlocked.Decrement(ref waitCount); if (decrementResult == 0 && outerDeferred.IsFulfilled == false) { outerDeferred.Reject(new Exception("None of the promises failed")); } } }); } return(outerDeferred.Promise); }
/// <summary> /// Creates an aggregate promise that completes after all the given promises complete. /// The aggregate promise resolves only if all inner promises resolves. If any inner promise /// fails then the aggregate promise will fail. /// </summary> /// <param name="promises">the promises to aggregate</param> /// <returns>the aggregate promise</returns> public static Promise WhenAll(List <Promise> promises) { List <Exception> aggregateExceptions = new List <Exception>(); Deferred outerDeferred = Deferred.Create(); int waitCount = promises.Count; foreach (var promise in promises) { promise.Finally((p) => { if (p.Exception != null) { lock (aggregateExceptions) { aggregateExceptions.Add(p.Exception); } } var decrementResult = Interlocked.Decrement(ref waitCount); if (decrementResult == 0) { if (aggregateExceptions.Count == 0) { outerDeferred.Resolve(); } else { outerDeferred.Reject(new AggregateException(aggregateExceptions.ToArray())); } } }); } return(outerDeferred.Promise); }