using System; using System.Diagnostics; namespace Implab { class PromiseFuncReaction : IResolvable { readonly Deferred m_next; readonly IDispatcher m_dispatcher; readonly Action> m_fulfilled; readonly Action> m_rejected; public IPromise Promise { get { return m_next.Promise; } } public PromiseFuncReaction(Action> fulfilled, Action> rejected, Deferred next, IDispatcher dispatcher) { m_next = next; m_fulfilled = fulfilled; m_rejected = rejected; m_dispatcher = dispatcher; } public void Resolve(TIn result) { if (m_fulfilled != null) { if (m_dispatcher != null) m_dispatcher.Enqueue(ResolveImpl, result); else ResolveImpl(result); } else { try { m_next.Resolve((TRet)(object)result); } catch(Exception error) { // handle cast exceptions m_next.Reject(error); } } } void ResolveImpl (TIn result) { m_fulfilled(result, m_next); } public void Reject(Exception error) { if (m_fulfilled != null) { if (m_dispatcher != null) m_dispatcher.Enqueue(RejectImpl, error); else RejectImpl(error); } else { m_next.Reject(error); } } void RejectImpl(Exception error) { m_rejected(error, m_next); } public static PromiseFuncReaction Create(Func fulfilled, Func rejected, IDispatcher dispatcher) { return new PromiseFuncReaction( fulfilled != null ? PromiseHandler.Create(fulfilled) : null, rejected != null ? PromiseHandler.Create(rejected) : null, new Deferred(), dispatcher ); } public static PromiseFuncReaction Create(Func> fulfilled, Func rejected, IDispatcher dispatcher) { return new PromiseFuncReaction( fulfilled != null ? PromiseHandler.Create(fulfilled) : null, rejected != null ? PromiseHandler.Create(rejected) : null, new Deferred(), dispatcher ); } public static PromiseFuncReaction Create(Func fulfilled, Func> rejected, IDispatcher dispatcher) { return new PromiseFuncReaction( fulfilled != null ? PromiseHandler.Create(fulfilled) : null, rejected != null ? PromiseHandler.Create(rejected) : null, new Deferred(), dispatcher ); } public static PromiseFuncReaction Create(Func> fulfilled, Func> rejected, IDispatcher dispatcher) { return new PromiseFuncReaction( fulfilled != null ? PromiseHandler.Create(fulfilled) : null, rejected != null ? PromiseHandler.Create(rejected) : null, new Deferred(), dispatcher ); } } }