AsyncComponent.ts
35 lines
| 1.0 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r49 | import { Cancellation } from "../Cancellation"; | ||
|
|
r170 | import { IAsyncComponent, ICancellation, ICancellable } from "../interfaces"; | ||
|
|
r49 | |||
|
|
r134 | const noop = () => void (0); | ||
|
|
r49 | export class AsyncComponent implements IAsyncComponent, ICancellable { | ||
|
|
r134 | _cancel: ((e: any) => void) = noop; | ||
|
|
r49 | |||
| _completion: Promise<void> = Promise.resolve(); | ||||
|
|
r54 | getCompletion() { return this._completion; } | ||
|
|
r49 | |||
| runOperation(op: (ct: ICancellation) => any, ct: ICancellation = Cancellation.none) { | ||||
| // create inner cancellation bound to the passed cancellation token | ||||
|
|
r54 | const inner = new Cancellation(cancel => { | ||
|
|
r49 | this._cancel = cancel; | ||
| }); | ||||
|
|
r54 | const guard = async () => { | ||
|
|
r49 | try { | ||
|
|
r170 | return op(Cancellation.combine(ct, inner)); | ||
|
|
r49 | } finally { | ||
| // after the operation is complete we need to cleanup the | ||||
| // resources | ||||
|
|
r134 | this._cancel = noop; | ||
|
|
r49 | } | ||
|
|
r54 | }; | ||
|
|
r49 | |||
| return this._completion = guard(); | ||||
| } | ||||
|
|
r59 | cancel(reason: any) { | ||
|
|
r134 | this._cancel(reason); | ||
|
|
r49 | } | ||
|
|
r54 | } | ||
