Created
October 23, 2018 07:44
-
-
Save heartAndRain/0a3e901913ad9053528f6ce2c0f5b46c to your computer and use it in GitHub Desktop.
CancelableAsyncTask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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