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

Add Result.fromCb Method #8

Closed
wants to merge 2 commits into from

Conversation

kadiryazici
Copy link

@kadiryazici kadiryazici commented Jul 8, 2022

We have Result.from but what if We want to use callback and use it's exception as Error and return value as Ok also it supports Promise, this method provides it.

I was using this method in my projects and it was really helpful while working with Promises or Exceptions, I thought that it would be nice if library includes this method.

Example

const user: Result<User, UserNotFoundError> = Result.fromCb(() => {
  const foundUser = findUser(); // Throws if cannot find 
  return foundUser
})

if(user.isErr()) {
  const userError = user.unwrapErr();
}

user.unwrap();

// Async
const user: Result<User, UserNotFoundError> = await Result.fromCb(async () => {
  const foundUser = await findUser(); // Throws if cannot find 
  return foundUser
})

const foo = Result<Foo, FooError> = await Result.fromCb(() => Promise.resolve(5));
const bar = Result<Bar, BarError> = await Result.fromCb(() => Promise.reject(new Error()));

@traverse1984
Copy link
Owner

Well, you might kick yourself - but this is built in: Result.safe.

There are a couple of differences between the implementations, so I'd suggest checking out the docs for safe: https://www.npmjs.com/package/oxide.ts#safe

@kadiryazici
Copy link
Author

@traverse1984 sorry my bad 😢 I should read carefully thanks.

@kadiryazici kadiryazici closed this Jul 8, 2022
@traverse1984
Copy link
Owner

No worries... appreciate your interest and you made a good implementation. Nice work.

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

Successfully merging this pull request may close these issues.

None yet

2 participants