/// <summary> /// Resolves when any in IPromise array is resolved /// Fails if all in IPromise array are failed /// </summary> /// <param name="collection">promises to complete</param> /// <returns>IPromise</returns> public static IPromise Race(params IPromise[] collection) { Deferred deferred = Deferred.GetFromPool(); if (collection.Length == 0) { deferred.Reject(new Exception("Deferred.Race called with empty array - no winner")); } else { int promisesToWait = collection.Length; for (int i = 0, maxi = collection.Length - 1; i <= maxi; i++) { collection[i].Done(() => { if (deferred.CurrentState == States.Pending) { deferred.Resolve(); } }); collection[i].Fail(ex => { promisesToWait--; if (deferred.CurrentState == States.Pending && promisesToWait == 0) { deferred.Reject(ex); } }); } } return(deferred); }
/// <summary> /// adds new promise constructor to current promise and returns wrapper that resolves with added promise /// A.Then(B) - returns promise that resolves when promise from B is resolved /// </summary> /// <param name="next">constructor for next promise</param> /// <returns>Promise</returns> public IPromise Then(Func <IPromise> next) { Deferred deferred = Deferred.GetFromPool(); Done(() => { IPromise promise = next(); promise.Done(() => deferred.Resolve()); promise.Fail(ex => deferred.Reject(ex)); }); Fail(ex => deferred.Reject(ex)); return(deferred); }
private static IPromise AllInternal(ICollection <IPromise> collection) { Deferred deferred = Deferred.GetFromPool(); if (collection.Count == 0) { deferred.Resolve(); } else { int promisesToComplete = collection.Count; foreach (IPromise element in collection) { element.Done(() => { promisesToComplete--; if (deferred.CurrentState == States.Pending && promisesToComplete == 0) { deferred.Resolve(); } }); element.Fail(ex => { if (deferred.CurrentState == States.Pending) { deferred.Reject(ex); } }); } } return(deferred); }