-
Notifications
You must be signed in to change notification settings - Fork 2
/
Task.ts
55 lines (48 loc) · 1.52 KB
/
Task.ts
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
import CancellationToken from "cancellationtoken";
/**
* A task is a promise with a CancellationToken
* It can inherit from a "parent" cancellationToken (canceling the parent will cancel the promise, if not already done)
*/
export interface Task<T> extends Promise<T> {
readonly cancellation: CancellationToken;
readonly cancel: (reason?: any)=>(void);
}
export function createTask<T>(
parentCancelation?: CancellationToken,
code?:(task: Task<T>)=>Promise<T>
):Task<T> {
let child:any = {};
let resolve: (value?: T | PromiseLike<T> | undefined) => void;
let reject: (reason?: any) => void;
const ret:any = new Promise<T>((tresolve, treject) => {
resolve = tresolve;
reject = treject;
});
const {token, cancel} = CancellationToken.create();
ret.cancellation = token;
ret.cancel = cancel;
(async ()=> {
const whenDone = (parentCancelation !== undefined)
? parentCancelation.onCancelled(cancel)
:undefined;
try {
if (code) {
let result: T;
try {
result = await code(ret);
} catch(e) {
ret.cancel=()=>{};
reject!(e);
return;
}
ret.cancel=()=>{};
resolve!(result);
}
} finally {
if (whenDone !== undefined) {
whenDone();
}
}
})();
return ret;
}