244
|
1 using System;
|
|
2 using System.Diagnostics;
|
|
3
|
|
4 namespace Implab {
|
|
5 /// <summary>
|
|
6 /// This class is responsible for the promise resolution, dispatching and chaining
|
|
7 /// </summary>
|
|
8 public class Deferred : IResolvable {
|
|
9
|
248
|
10 readonly Promise m_promise;
|
244
|
11 readonly IDispatcher m_dispatcher;
|
|
12
|
248
|
13 internal Deferred(IDispatcher dispatcher) : this(new Promise(), dispatcher) {
|
|
14 }
|
|
15
|
|
16 internal Deferred(Promise promise, IDispatcher dispatcher) {
|
244
|
17 Debug.Assert(promise != null);
|
|
18 m_promise = promise;
|
|
19 m_dispatcher = dispatcher;
|
|
20 }
|
|
21
|
|
22 public IPromise Promise {
|
|
23 get { return m_promise; }
|
|
24 }
|
|
25
|
|
26 public void Reject(Exception error) {
|
248
|
27 if (error is PromiseTransientException)
|
|
28 error = ((PromiseTransientException)error).InnerException;
|
|
29
|
|
30 m_promise.RejectPromise(error);
|
244
|
31 }
|
|
32
|
|
33 public void Resolve() {
|
248
|
34 m_promise.ResolvePromise();
|
244
|
35 }
|
|
36
|
|
37 public void Resolve(IPromise thenable) {
|
|
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 else if (m_dispatcher != null)
|
|
44 // dispatch (see ecma-262/6.0: 25.4.1.3.2 Promise Resolve Functions)
|
248
|
45 m_dispatcher.Enqueue(Chain, thenable);
|
244
|
46 else
|
245
|
47 Chain(thenable);
|
244
|
48 }
|
|
49
|
|
50 void Chain(IPromise thenable) {
|
|
51 try {
|
|
52 thenable.Then(this);
|
|
53 } catch (Exception err) {
|
|
54 Reject(err);
|
|
55 }
|
|
56 }
|
|
57 }
|
|
58 } |