Chain some async tasks in fp-ts retaining every task's result Chain some async tasks in fp-ts retaining every task's result typescript typescript

Chain some async tasks in fp-ts retaining every task's result


Depending on how many times you'll need to access the intermediate results in the following computation, I would suggest either using Do from fp-ts-contrib (an approximation of Haskell's do notation), or carry the intermediate results over via manual mapping.

Given:

import * as TE from "fp-ts/lib/TaskEither";declare function getFoo(a: string): TE.TaskEither<unknown, Foo>;declare function getBar(foo: Foo): TE.TaskEither<unknown, Bar>;declare function mkFooBar(foo: Foo, bar: Bar): TE.TaskEither<unknown, FooBar>;

Example with Do:

import { Do } from "fp-ts-contrib/lib/Do";function main2(): TE.TaskEither<unknown, FooBar> {  return Do(TE.taskEither)    .bind("foo", getFoo("a"))    .bindL("bar", ({ foo }) => getBar(foo))    .bindL("fooBar", ({ foo, bar }) => mkFooBar(foo, bar))    .return(({ fooBar }) => fooBar);}

Example mapping manually:

import { pipe } from "fp-ts/lib/pipeable";function main3(): TE.TaskEither<unknown, FooBar> {  return pipe(    getFoo("a"),    TE.chain(foo =>      pipe(        getBar(foo),        TE.map(bar => ({ foo, bar }))      )    ),    TE.chain(({ foo, bar }) => mkFooBar(foo, bar))  );}