-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d128165
commit 9564c04
Showing
2 changed files
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters