8000 feat: add tryCatchAsync · kdt310722/utils@f8f8fa4 · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Commit f8f8fa4

Browse files
committed
feat: add tryCatchAsync
1 parent b60e2a1 commit f8f8fa4

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/function/function.ts

+13
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { Nullable } from '../common'
2+
import type { Awaitable } from '../promise'
23
import type { Fn } from './types'
34

45
export const isFunction = <T extends Fn>(value: unknown): value is T => typeof value === 'function'
@@ -34,3 +35,15 @@ export function tryCatch<T>(fn: () => T, fallback: T, throwsIf?: (error: unknown
3435
return fallback
3536
}
3637
}
38+
39+
export async function tryCatchAsync<T>(fn: () => Promise<T>, fallback: Awaitable<T>, throwsIf?: (error: unknown) => boolean) {
40+
try {
41+
return await fn()
42+
} catch (error) {
43+
if (throwsIf?.(error)) {
44+
throw error
45+
}
46+
47+
return fallback
48+
}
49+
}

0 commit comments

Comments
 (0)
0