AsyncComponent.ts
39 lines
| 1.2 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r13 | import { Cancellation } from "../Cancellation"; | |
|
|
r22 | import { IAsyncComponent, ICancellation, ICancellable, IDestroyable } from "../interfaces"; | |
| import { destroy } from "../safe"; | |||
|
|
r9 | ||
|
|
r22 | export class AsyncComponent implements IAsyncComponent, ICancellable { | |
| _cancel: (e) => void; | |||
|
|
r13 | _completion: Promise<void> = Promise.resolve(); | |
|
|
r9 | ||
| getCompletion() { return this._completion }; | |||
|
|
r13 | runOperation(op: (ct: ICancellation) => any, ct: ICancellation = Cancellation.none) { | |
|
|
r22 | // create inner cancellation bound to the passed cancellation token | |
| let h: IDestroyable; | |||
| let inner = new Cancellation(cancel => { | |||
| this._cancel = cancel; | |||
| h = ct.register(cancel); | |||
| }); | |||
|
|
r13 | // TODO create cancellation source here | |
|
|
r22 | let guard = async () => { | |
| try { | |||
| await op(inner); | |||
| } finally { | |||
| // after the operation is complete we need to cleanup the | |||
| // resources | |||
| destroy(h); | |||
| this._cancel = null; | |||
| } | |||
|
|
r13 | } | |
|
|
r9 | ||
|
|
r13 | return this._completion = guard(); | |
|
|
r9 | } | |
|
|
r22 | ||
| cancel(reason) { | |||
| if (this._cancel) | |||
| this._cancel(reason); | |||
| } | |||
|
|
r9 | } |
