Created
November 25, 2019 13:09
-
-
Save gunzip/bc5f312d479fea1f3299b97247f46a49 to your computer and use it in GitHub Desktop.
taskeither
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
import { array } from "fp-ts/lib/Array"; | |
import { left2v, taskEither, tryCatch } from "fp-ts/lib/TaskEither"; | |
const t1 = tryCatch<Error, string>( | |
// some function that returns a promise or an either | |
async () => "someValue1", | |
// "catch" handler | |
() => Error("t1 error") | |
); | |
// no need to type tryCatch, type is inferred from returned values | |
const t2 = tryCatch(async () => "anotherValue2", () => Error("t2 error")); | |
const t3 = tryCatch(async () => "anotherValue3", () => Error("t3 error")); | |
array | |
.sequence(taskEither)([t1, t2, t3]) | |
.run() | |
// tslint:disable-next-line: no-console | |
.then(console.log) | |
// tslint:disable-next-line: no-console | |
.catch(e => console.error("*ERR", e)); // --> right(["someValue1", "anotherValue2", "anotherValue3"]) | |
// suppose t2 throws / reject | |
const t2exp = tryCatch( | |
async () => { | |
throw new Error("t2 exception"); | |
}, | |
e => e | |
); | |
array | |
.sequence(taskEither)([t1, t2exp, t3]) | |
.run() | |
// tslint:disable-next-line: no-console | |
.then(console.log) | |
// tslint:disable-next-line: no-console | |
.catch(e => console.error("*ERR", e)); // --> left(Error: t2 exception) | |
// suppose t2 returns a left | |
const t2left = left2v(Error("some left error")); | |
array | |
.sequence(taskEither)([t1, t2left, t3]) | |
.run() | |
// tslint:disable-next-line: no-console | |
.then(console.log) | |
// tslint:disable-next-line: no-console | |
.catch(e => console.error("*ERR", e)); // --> left(Error: some left error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment