Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can EitherAsync.chain support both Either and EitherAsync? #731

Open
lightDer opened this issue Oct 12, 2024 · 2 comments
Open

Can EitherAsync.chain support both Either and EitherAsync? #731

lightDer opened this issue Oct 12, 2024 · 2 comments

Comments

@lightDer
Copy link

Hi! It's really a neat and lightweight libs.
I wonder if EitherAsync.chain can support both Either and EitherAsync?

For example, if I want to chain getTitle, I need add async in the chain method.
Or any recommendations for handling this? Thanks.

async function getPost (postId: number): Promise<Either<Error, Post>> {
  const response = await fetch(`/posts/${postId}`);
  return response
    ? Right((response.json() as unknown) as Post)
    : Left(new Error(`Problem fetching post with id: ${postId}`));
}

function getTitle (post: Post): Either<Error, string> {
  return post.title
    ? Right(post.title)
    : Left(new Error("This post should have a title"));
}

function getPostTitle (req: Request): EitherAsync<Error, string> {
  return EitherAsync.liftEither(validateRequest(req))
    .chain((request) => getPost(request.postId))
    .chain(async (post) => getTitle(post));
}
@leepowelldev
Copy link

I too would like to see this - the EitherAsync api is great - but I end up littering the code with lots of EitherAsync.liftEither - if there's a nicer way to handle I'd also like to know.

@probablykabari
Copy link

Your getPostTitle function can be written as:

function getPostTitle (req: Request): EitherAsync<Error, string> {
  return EitherAsync(async ({ fromPromise, liftEither }) => {
     const request = await liftEither(validateRequest(req))
     const post = await fromPromise(getPost(request.postId))
     return await liftEither(getTitle(post))
  })
}

I often find this to be cleaner for composing functions than the chained interface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants