@taraflex/cancelation-token
Advanced tools
+1
-1
| { | ||
| "name": "@taraflex/cancelation-token", | ||
| "version": "0.0.1", | ||
| "version": "0.0.2", | ||
| "description": "", | ||
@@ -5,0 +5,0 @@ "license": "ISC", |
-60
| type Connections = Set<CancelationTokenConnection> | ||
| export interface IDisposable { | ||
| dispose(): void; | ||
| } | ||
| class CancelationTokenConnection implements IDisposable { | ||
| constructor(private connections: Connections, private readonly cb: Function) { | ||
| connections.add(this); | ||
| } | ||
| run(v?: any) { | ||
| try { | ||
| this.cb(v); | ||
| } finally { | ||
| this.dispose(); | ||
| } | ||
| } | ||
| dispose() { | ||
| if (this.connections) { | ||
| this.connections.delete(this); | ||
| this.connections = null; | ||
| } | ||
| } | ||
| } | ||
| export class CancelationTokenError extends Error { } | ||
| export class CancelationToken { | ||
| private readonly connections: Connections = new Set(); | ||
| private _canceled = false | ||
| get canceled() { | ||
| return this._canceled; | ||
| } | ||
| check() { | ||
| if (this._canceled) { | ||
| throw new CancelationTokenError(); | ||
| } | ||
| } | ||
| connect(cb: Function): IDisposable { | ||
| this.check(); | ||
| return new CancelationTokenConnection(this.connections, cb); | ||
| } | ||
| cancel(v?: any) { | ||
| if (!this._canceled) { | ||
| this._canceled = true; | ||
| let err = undefined; | ||
| this.connections.forEach(c => { | ||
| try { | ||
| c.run(v); | ||
| } catch (e) { | ||
| err = e || err; | ||
| } | ||
| }); | ||
| this.connections.clear(); | ||
| if (err !== undefined) { | ||
| throw err; | ||
| } | ||
| } | ||
| } | ||
| } |
2794
-35.53%4
-20%95
-36.67%