-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathAsyncTask.ts
More file actions
45 lines (40 loc) · 1.31 KB
/
AsyncTask.ts
File metadata and controls
45 lines (40 loc) · 1.31 KB
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
36
37
38
39
40
41
42
43
44
45
import { defaultErrorHandler, loggingErrorHandler } from './Logger'
import { isPromise } from './Utils'
import { Task } from './Task'
export function isAsyncTask(task: Task | AsyncTask): task is AsyncTask {
return (task as AsyncTask).isAsync === true
}
export class AsyncTask {
public isAsync = true
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 {
void this.executeAsync(jobId)
}
executeAsync(jobId?: string): Promise<unknown> {
this.isExecuting = true
return 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
})
}
}