-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPromise.cs
70 lines (61 loc) · 1.79 KB
/
Promise.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Maverick
{
public class Promise
{
public Promise(Func<object> asyncOp)
{
Scheduler.Request();
task = new Task(() =>
{
try
{
_result = asyncOp();
_success = true;
}
catch(Exception e)
{
_taskException = e;
if (_exceptionCallback != null)
{
Scheduler.Enqueue(() => _exceptionCallback(_taskException));
}
}
if (_success && _successCallback != null)
{
Scheduler.Enqueue(() => _successCallback(_result));
}
});
task.Start();
}
readonly Task task;
bool _success = false;
dynamic _result = null;
Action<object> _successCallback;
public Promise success(Action<object> cb)
{
_successCallback = cb;
if (_success)
{
Scheduler.Enqueue(() => _successCallback(_result));
}
return this;
}
Exception _taskException;
Action<object> _exceptionCallback;
public Promise error(Action<object> cb)
{
_exceptionCallback = cb;
if (_taskException != null)
{
Scheduler.Enqueue(() => _exceptionCallback(_taskException));
}
return this;
}
}
}