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
|
|
10 readonly AbstractPromise m_promise;
|
|
11 readonly IDispatcher m_dispatcher;
|
|
12
|
|
13 internal Deferred(AbstractPromise promise, IDispatcher dispatcher) {
|
|
14 Debug.Assert(promise != null);
|
|
15 m_promise = promise;
|
|
16 m_dispatcher = dispatcher;
|
|
17 }
|
|
18
|
|
19 public IPromise Promise {
|
|
20 get { return m_promise; }
|
|
21 }
|
|
22
|
|
23 public void Reject(Exception error) {
|
|
24 m_promise.Reject(error);
|
|
25 }
|
|
26
|
|
27 public void Resolve() {
|
|
28 m_promise.Resolve();
|
|
29 }
|
|
30
|
|
31 public void Resolve(IPromise thenable) {
|
|
32 if (thenable == null)
|
|
33 Reject(new Exception("The promise or task are expected"));
|
|
34 if (thenable == m_promise)
|
|
35 Reject(new Exception("The promise cannot be resolved with oneself"));
|
|
36
|
|
37 else if (m_dispatcher != null)
|
|
38 // dispatch (see ecma-262/6.0: 25.4.1.3.2 Promise Resolve Functions)
|
245
|
39 m_dispatcher.Enqueue(() => Chain(thenable));
|
244
|
40 else
|
245
|
41 Chain(thenable);
|
244
|
42 }
|
|
43
|
|
44 void Chain(IPromise thenable) {
|
|
45 try {
|
|
46 thenable.Then(this);
|
|
47 } catch (Exception err) {
|
|
48 Reject(err);
|
|
49 }
|
|
50 }
|
|
51 }
|
|
52 } |