246
|
1 using System;
|
|
2 using System.Diagnostics;
|
|
3
|
|
4 namespace Implab {
|
|
5 public class Deferred<T> : IResolvable<T> {
|
248
|
6 readonly Promise<T> m_promise;
|
246
|
7
|
249
|
8 internal Deferred() {
|
|
9 m_promise = new Promise<T>();
|
248
|
10 }
|
|
11
|
249
|
12 protected Deferred(Promise<T> promise) {
|
246
|
13 Debug.Assert(promise != null);
|
|
14 m_promise = promise;
|
|
15 }
|
|
16
|
|
17 public IPromise<T> Promise {
|
|
18 get { return m_promise; }
|
|
19 }
|
|
20
|
249
|
21 public void Cancel() {
|
|
22 Reject(new OperationCanceledException());
|
|
23 }
|
|
24
|
|
25 public virtual void Reject(Exception error) {
|
248
|
26 if (error is PromiseTransientException)
|
|
27 error = ((PromiseTransientException)error).InnerException;
|
|
28
|
|
29 m_promise.RejectPromise(error);
|
246
|
30 }
|
|
31
|
249
|
32 public virtual void Resolve(T value) {
|
248
|
33 m_promise.ResolvePromise(value);
|
246
|
34 }
|
|
35
|
249
|
36 public virtual void Resolve(IPromise<T> thenable) {
|
246
|
37 if (thenable == null)
|
|
38 Reject(new Exception("The promise or task are expected"));
|
|
39 if (thenable == m_promise)
|
|
40 Reject(new Exception("The promise cannot be resolved with oneself"));
|
|
41
|
|
42 try {
|
|
43 thenable.Then(this);
|
|
44 } catch (Exception err) {
|
|
45 Reject(err);
|
|
46 }
|
|
47 }
|
|
48 }
|
|
49 } |