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