diff --git a/docs/async/errorFirst.mdx b/docs/async/errorFirst.mdx new file mode 100644 index 00000000..aa3ea66b --- /dev/null +++ b/docs/async/errorFirst.mdx @@ -0,0 +1,29 @@ +--- +title: errorFirst +description: Coerce a promise into a `[error, value]` tuple +--- + +## Description + +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 +import * as _ from 'radashi' + +async function getData() { + return 'data' +} + +const [error, data] = await _.errorFirst(getData()) + +if (error) { + console.error(error) +} else { + console.log(data) // data +} +``` diff --git a/tests/async/errorFirst.test.ts b/tests/async/errorFirst.test.ts new file mode 100644 index 00000000..9eed06e4 --- /dev/null +++ b/tests/async/errorFirst.test.ts @@ -0,0 +1,35 @@ +import { errorFirst } from 'radashi' + +test('resolves with [null, value] when the promise resolves', async () => { + const promise = Promise.resolve('value') + const result = await errorFirst(promise) + expect(result).toEqual([null, 'value']) +}) + +test('rejects with [error, null] when the promise rejects', async () => { + const promise = Promise.reject(new Error('error')) + const result = await errorFirst(promise) + expect(result).toEqual([new Error('error'), null]) +}) + +test('calls the function and resolves with [null, value] when the function resolves', async () => { + const fn = async () => 'value' + const result = await errorFirst(fn) + expect(result).toEqual([null, 'value']) +}) + +test('calls the function and rejects with [error, null] when the function rejects', async () => { + const fn = async () => { + throw new Error('error') + } + const result = await errorFirst(fn) + expect(result).toEqual([new Error('error'), null]) +}) + +test('calls the function and rejects with [error, null] when the function throws synchronously', async () => { + const fn = () => { + throw new Error('error') + } + const result = await errorFirst(fn) + expect(result).toEqual([new Error('error'), null]) +})