Skip to content
This repository has been archived by the owner on May 3, 2021. It is now read-only.

Commit

Permalink
fix: resolve task_either tryCatch lazily
Browse files Browse the repository at this point in the history
Unlike fp-ts the task_either tryCatch is meant to lazily evaluate
a thunk within a try catch block, deferring the computation. The
fp-ts implementation is covered by the fromFailableTask
constructor.

This fix ensures that tryCatch evaluates lazily by wrapping it in
its own thunk.

Note: Will need to add this to the trampoline impl later.

fixes #2
  • Loading branch information
baetheus committed Oct 14, 2020
1 parent c90a933 commit 240566d
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions task_either.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ export const right = <E = never, A = never>(right: A): TaskEither<E, A> =>
export const tryCatch = <E, A>(
f: Lazy<A>,
onError: (e: unknown) => E,
): TaskEither<E, A> => {
try {
return right(f());
} catch (e) {
return left(onError(e));
}
};
): TaskEither<E, A> =>
() => {
try {
return Promise.resolve(E.right(f()));
} catch (e) {
return Promise.resolve(E.left(onError(e)));
}
};

export const fromFailableTask = <E, A>(onError: (e: unknown) => E) =>
(ta: T.Task<A>): TaskEither<E, A> =>
Expand Down Expand Up @@ -113,3 +114,12 @@ export const { bimap, mapLeft } = D.createPipeableBifunctor(Bifunctor);
export const sequenceTuple = S.createSequenceTuple(Apply);

export const sequenceStruct = S.createSequenceStruct(Apply);

const a = (): string => {
console.log("a was run.");
throw new Error("Oh No!");
};

const b = tryCatch(a, (e) => `Caught an error, ${e}`);
console.log("This should happen first..");
b().then((r) => console.log(r));

0 comments on commit 240566d

Please sign in to comment.