/// <summary> /// Return a new promise with a different value. /// May also change the type of the value. /// </summary> public IPromise <ConvertedT> Transform <ConvertedT>(Func <PromisedT, ConvertedT> transform) { Argument.NotNull(() => transform); var resultPromise = new Promise <ConvertedT>(); resultPromise.WithName(Name); Action <PromisedT> resolveHandler = v => { resultPromise.Resolve(transform(v)); }; Action <Exception> rejectHandler = ex => { resultPromise.Reject(ex); }; ActionHandlers(resultPromise, resolveHandler, rejectHandler); return(resultPromise); }
/// <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> /// 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 => { onRejected(ex); resultPromise.Reject(ex); }; ActionHandlers(resultPromise, resolveHandler, rejectHandler); return(resultPromise); }