AsyncComponent.ts
41 lines
| 1.2 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r49 | import { Cancellation } from "../Cancellation"; | ||
| import { IAsyncComponent, ICancellation, ICancellable, IDestroyable } from "../interfaces"; | ||||
| import { destroy } from "../safe"; | ||||
|
|
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 | ||||
| let h: IDestroyable; | ||||
|
|
r54 | const inner = new Cancellation(cancel => { | ||
|
|
r49 | |||
| this._cancel = cancel; | ||||
| h = ct.register(cancel); | ||||
| }); | ||||
| // TODO create cancellation source here | ||||
|
|
r54 | const guard = async () => { | ||
|
|
r49 | try { | ||
| await op(inner); | ||||
| } finally { | ||||
| // after the operation is complete we need to cleanup the | ||||
| // resources | ||||
| destroy(h); | ||||
|
|
r134 | this._cancel = noop; | ||
|
|
r49 | } | ||
|
|
r54 | }; | ||
|
|
r49 | |||
| return this._completion = guard(); | ||||
| } | ||||
|
|
r59 | cancel(reason: any) { | ||
|
|
r134 | this._cancel(reason); | ||
|
|
r49 | } | ||
|
|
r54 | } | ||
