Ejemplo n.º 1
0
 /// <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 IFpromise Sequence(IEnumerable <Func <IFpromise> > fns)
 {
     return(fns.Aggregate(
                Fpromise.Resolved(),
                (prevFpromise, fn) =>
     {
         return prevFpromise.Then(() => fn());
     }
                ));
 }
Ejemplo n.º 2
0
        /// <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 IFpromise <IEnumerable <FpromisedT> > All(IEnumerable <IFpromise <FpromisedT> > promises)
        {
            var promisesArray = promises.ToArray();

            if (promisesArray.Length == 0)
            {
                return(Fpromise <IEnumerable <FpromisedT> > .Resolved(EnumerableExtensions.Empty <FpromisedT>()));
            }

            var remainingCount = promisesArray.Length;
            var results        = new FpromisedT[remainingCount];
            var resultFpromise = new Fpromise <IEnumerable <FpromisedT> >();

            resultFpromise.WithName("All");

            promisesArray.Each((promise, index) =>
            {
                promise
                .Catch(ex =>
                {
                    if (resultFpromise.CurState == FpromiseState.Pending)
                    {
                        // If a promise errorred and the result promise is still pending, reject it.
                        resultFpromise.Reject(ex);
                    }
                })
                .Then(result =>
                {
                    results[index] = result;

                    --remainingCount;
                    if (remainingCount <= 0)
                    {
                        // This will never happen if any of the promises errorred.
                        resultFpromise.Resolve(results);
                    }
                })
                .Done();
            });

            return(resultFpromise);
        }