Skip to content

Commit

Permalink
tweak some things
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Feb 7, 2025
1 parent a8b7eac commit 5bceb2b
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/async/errorFirst.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
import { isFunction } from 'radashi'

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

export type ErrorFirst<T, Error = unknown> = [null, T] | [Error, null]
export type ErrorFirst<TResult> = [null, TResult] | [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]`.
*
* @example
* ```ts
* const [error, data] = await errorFirst(async () => 'data')
* if (error) {
* console.error(error)
* } else {
* console.log(data)
* }
* ```
*/
export function errorFirst<T, Args extends any[]>(
fn: (...args: Args) => Promise<T>,
Expand All @@ -30,5 +40,5 @@ export function errorFirst<T>(
promise = Promise.reject(error)
}
}
return promise.then(right, left)
return promise.then(fulfill, reject)
}

0 comments on commit 5bceb2b

Please sign in to comment.