Skip to content

Commit

Permalink
chore: add docs and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Feb 6, 2025
1 parent c376fb1 commit a8b7eac
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
29 changes: 29 additions & 0 deletions docs/async/errorFirst.mdx
Original file line number Diff line number Diff line change
@@ -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
}
```
35 changes: 35 additions & 0 deletions tests/async/errorFirst.test.ts
Original file line number Diff line number Diff line change
@@ -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])
})

0 comments on commit a8b7eac

Please sign in to comment.