view Implab/Deferred`1.cs @ 248:5cb4826c2c2a v3

Added awaiters to promises Added static methods to Promise Resolve, Reject, All. Updated promise helpers
author cin
date Tue, 30 Jan 2018 01:37:17 +0300
parents 5aa9cfbe56c3
children d82909310094
line wrap: on
line source

using System;
using System.Diagnostics;

namespace Implab {
    public class Deferred<T> : IResolvable<T> {
        readonly Promise<T> m_promise;
        readonly IDispatcher m_dispatcher;

        internal Deferred(IDispatcher dispatcher) : this(new Promise<T>(), dispatcher) {
        }

        internal Deferred(Promise<T> promise, IDispatcher dispatcher) {
            Debug.Assert(promise != null);
            m_promise = promise;
            m_dispatcher = dispatcher;
        }

        public IPromise<T> Promise {
            get { return m_promise; }
        }

        public void Reject(Exception error) {
            if (error is PromiseTransientException)
                error = ((PromiseTransientException)error).InnerException;

            m_promise.RejectPromise(error);
        }

        public void Resolve(T value) {
            m_promise.ResolvePromise(value);
        }

        public void Resolve(IPromise<T> thenable) {
            if (thenable == null)
                Reject(new Exception("The promise or task are expected"));
            if (thenable == m_promise)
                Reject(new Exception("The promise cannot be resolved with oneself"));

            else if (m_dispatcher != null)
                // dispatch (see ecma-262/6.0: 25.4.1.3.2 Promise Resolve Functions)
                m_dispatcher.Enqueue(Chain, thenable);
            else
                Chain(thenable);
        }

        void Chain(IPromise<T> thenable) {
            try {
                thenable.Then(this);
            } catch (Exception err) {
                Reject(err);
            }
        }
    }
}