traverse1984 / oxide.ts

Rust's Option<T> and Result<T, E>, implemented for TypeScript.
MIT License
509 stars 19 forks source link

Add `Result.fromCb` Method #8

Closed kadiryazici closed 2 years ago

kadiryazici commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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

traverse1984 commented 2 years ago

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