-
Notifications
You must be signed in to change notification settings - Fork 25
/
AsyncTask.ts
35 lines (32 loc) · 1.04 KB
/
AsyncTask.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { defaultErrorHandler, loggingErrorHandler } from './Logger'
import { isPromise } from './Utils'
export class AsyncTask {
public isExecuting: boolean
private readonly id: string
private readonly handler: (taskId?: string, jobId?: string) => Promise<unknown>
private readonly errorHandler: (err: Error) => void | Promise<void>
constructor(
id: string,
handler: (taskId?: string, jobId?: string) => Promise<unknown>,
errorHandler?: (err: Error) => void,
) {
this.id = id
this.handler = handler
this.errorHandler = errorHandler || defaultErrorHandler(this.id)
this.isExecuting = false
}
execute(jobId?: string): void {
this.isExecuting = true
this.handler(this.id, jobId)
.catch((err: Error) => {
const errorHandleResult = this.errorHandler(err)
if (isPromise(errorHandleResult)) {
// If we fail while handling an error, oh well
errorHandleResult.catch(loggingErrorHandler(err))
}
})
.finally(() => {
this.isExecuting = false
})
}
}