-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTimeout.ts
30 lines (27 loc) · 964 Bytes
/
Timeout.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
import CancellationToken from "cancellationtoken";
import {createTask} from "./Task.js";
export default async function Timeout<T>(ct: CancellationToken, code: (ct:CancellationToken)=>Promise<T>, timeout:number, errorProvider:()=>Error)
{
ct.throwIfCancelled();
return await createTask(ct, async (task)=> {
let expired : boolean = false;
let timeObj:NodeJS.Timeout|undefined = setTimeout(()=> {
timeObj = undefined;
expired = true;
task.cancel();
}, timeout);
try {
return await code(task.cancellation);
} catch(e) {
if (e instanceof CancellationToken.CancellationError && !ct.isCancelled && expired) {
// Cancelation on our side.
throw errorProvider();
}
throw e;
} finally {
if (timeObj !== undefined) {
clearTimeout(timeObj);
}
}
});
}