Пример #1
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 IPromise <IEnumerable <PromisedT> > All(IEnumerable <IPromise <PromisedT> > promises)
        {
            var promisesArray = promises.ToArray();

            if (promisesArray.Length == 0)
            {
                return(Promise <IEnumerable <PromisedT> > .Resolved(LinqExts.Empty <PromisedT>()));
            }

            var remainingCount = promisesArray.Length;
            var results        = new PromisedT[remainingCount];
            var resultPromise  = new Promise <IEnumerable <PromisedT> >();

            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(result =>
                {
                    results[index] = result;

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

            return(resultPromise);
        }