Skip to content

Commit

Permalink
feat: add errorFirst function
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jul 10, 2024
1 parent d128165 commit 9564c04
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/async/errorFirst.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { isFunction } from 'radashi'

const left = <Error>(error: Error): [Error, null] => [error, null]
const right = <T>(value: T): [null, T] => [null, value]

export type ErrorFirst<T, Error = unknown> = [null, T] | [Error, null]

/**
* Call an async function and return a promise that resolves to an
* array of the error and the value.
*
* - If the promise resolves, the result is `[null, value]`.
* - If the promise rejects, the result is `[error, null]`.
*/
export function errorFirst<T, Args extends any[]>(
fn: (...args: Args) => Promise<T>,
...args: Args
): Promise<ErrorFirst<T>>

export function errorFirst<T>(promise: Promise<T>): Promise<ErrorFirst<T>>

export function errorFirst<T>(
promise: Promise<T> | ((...args: any[]) => Promise<T>),
...args: any[]
): Promise<ErrorFirst<T>> {
if (isFunction(promise)) {
try {
promise = promise(...args)
} catch (error) {
promise = Promise.reject(error)
}
}
return promise.then(right, left)
}
1 change: 1 addition & 0 deletions src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export * from './array/zipToObject.ts'
export * from './async/AggregateError.ts'
export * from './async/all.ts'
export * from './async/defer.ts'
export * from './async/errorFirst.ts'
export * from './async/guard.ts'
export * from './async/map.ts'
export * from './async/parallel.ts'
Expand Down

0 comments on commit 9564c04

Please sign in to comment.