Skip to content

Commit

Permalink
Add tryCatchK in TaskEither module
Browse files Browse the repository at this point in the history
  • Loading branch information
DenisFrezzato authored and gcanti committed Feb 13, 2020
1 parent 87eb41a commit 77157b1
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
16 changes: 16 additions & 0 deletions docs/modules/TaskEither.ts.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ Added in v2.0.0
- [taskEitherSeq](#taskeitherseq)
- [taskify](#taskify)
- [tryCatch](#trycatch)
- [tryCatchK](#trycatchk)

---

Expand Down Expand Up @@ -559,3 +560,18 @@ tryCatch(() => Promise.reject('error'), String)().then(result => {
```

Added in v2.0.0

# tryCatchK

Converts a function returning a `Promise` to one returning a `TaskEither`.

**Signature**

```ts
export function tryCatchK<E, A extends Array<unknown>, B>(
f: (...a: A) => Promise<B>,
onRejected: (reason: unknown) => E
): (...a: A) => TaskEither<E, B> { ... }
```

Added in v2.5.0
12 changes: 12 additions & 0 deletions src/TaskEither.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,18 @@ export function chainIOEitherK<E, A, B>(f: (a: A) => IOEither<E, B>): (ma: TaskE
return chain(fromIOEitherK(f))
}

/**
* Converts a function returning a `Promise` to one returning a `TaskEither`.
*
* @since 2.5.0
*/
export function tryCatchK<E, A extends Array<unknown>, B>(
f: (...a: A) => Promise<B>,
onRejected: (reason: unknown) => E
): (...a: A) => TaskEither<E, B> {
return (...a) => tryCatch(() => f(...a), onRejected)
}

/**
* @since 2.0.0
*/
Expand Down
14 changes: 14 additions & 0 deletions test/TaskEither.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,4 +375,18 @@ describe('TaskEither', () => {
const x = await pipe(_.right('a'), _.chainIOEitherK(f))()
assert.deepStrictEqual(x, E.right(1))
})

describe('tryCatchK', () => {
const handleRejection = () => 'rejected'

it('resolving', () => {
const fOk = (n: number, s: string) => Promise.resolve(n + s.length)
return _.tryCatchK(fOk, handleRejection)(2, '1')().then(x => assert.deepStrictEqual(x, E.right(3)))
})

it('rejecting', () => {
const fReject = () => Promise.reject()
return _.tryCatchK(fReject, handleRejection)()().then(x => assert.deepStrictEqual(x, E.left('rejected')))
})
})
})

0 comments on commit 77157b1

Please sign in to comment.