Skip to content

Commit

Permalink
fix: use optional error type and nulls in response
Browse files Browse the repository at this point in the history
  • Loading branch information
dvlden committed Jan 23, 2023
1 parent f4d25e8 commit 843ec77
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 22 deletions.
19 changes: 7 additions & 12 deletions tests/index.test.ts → src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import { it } from '../src/index'
import { describe, expect, test } from 'vitest'
import { it } from './index'

describe('index.ts', () => {
const resolve = { status: true }
const reject = new Error('Give me a reason.')
const defaultReject = new Error('Rejection reason unspecified.')

describe('result', () => {
test('result should contain what promise resolves', async () => {
const [res1] = await it(Promise.resolve(resolve))
const [res2] = await it(Promise.all([Promise.resolve('one'), Promise.resolve('two')]))
const [res2] = await it(
Promise.all([Promise.resolve('one'), Promise.resolve('two')]),
)

expect(res1).toEqual(resolve)
expect(res2).toEqual(['one', 'two'])
})

test('result should be `undefined` on rejection', async () => {
test('result should be `null` on rejection', async () => {
const [res] = await it(Promise.reject())

expect(res).toBeUndefined()
expect(res).toBeNull()
})
})

Expand All @@ -28,13 +30,6 @@ describe('index.ts', () => {
expect(err).toBeNull()
})

test('error should be `default` on rejection without a message', async () => {
const [_, err] = await it(Promise.reject())

expect(err).toBeInstanceOf(Error)
expect(err!.message).toBe(defaultReject.message)
})

test('error should be what promise rejects', async () => {
const [_, err] = await it(Promise.reject(reject))

Expand Down
14 changes: 4 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
type Ok<T> = Readonly<[T, null]>
type Err<T> = Readonly<[undefined, T]>
type Err<T> = Readonly<[null, T]>
type Result<O, E> = Promise<Ok<O> | Err<E>>

export const it = <T>(
promise: Promise<T>
): Result<T, Error> => {
export const it = <T, F = Error>(promise: Promise<T>): Result<T, F> => {
return promise
.then<Ok<T>>(
(res: T) => [res, null]
)
.catch<Err<Error>>(
(err?: Error) => [undefined, err || new Error('Rejection reason unspecified.')]
)
.then<Ok<T>>((res: T) => [res, null])
.catch<Err<F>>((err: F) => [null, err])
}

0 comments on commit 843ec77

Please sign in to comment.