Skip to content

Instantly share code, notes, and snippets.

@heartAndRain
Created October 23, 2018 07:44
Show Gist options
  • Save heartAndRain/0a3e901913ad9053528f6ce2c0f5b46c to your computer and use it in GitHub Desktop.
Save heartAndRain/0a3e901913ad9053528f6ce2c0f5b46c to your computer and use it in GitHub Desktop.
CancelableAsyncTask
export default class CancelableAsyncTask {
private do: (...args: any[]) => Promise<any>;
private running: boolean;
private args: any[];
constructor(doPromise: (...args: any[]) => Promise<any>, ...args: any[]) {
this.do = doPromise;
this.running = false;
this.args = args;
}
private afterTimeDo(
time: number,
doSomething: (...args: any[]) => Promise<any>,
args: any[],
) {
return new Promise<any>((resolve, reject) => {
setTimeout(async () => {
try {
const value = await doSomething(...args);
resolve(value);
} catch (error) {
reject(error);
}
}, time);
});
}
public async executePerTime(time: number, cb: (value: any) => void) {
this.running = true;
cb(await this.do(...this.args));
while (this.running) {
cb(await this.afterTimeDo(time, this.do, this.args));
}
}
public cancel() {
this.running = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment