JSMonk / sweet-monads

The library which provides useful monads, interfaces, and lazy iterators.
MIT License
343 stars 22 forks source link

Proposal: `fromTry` and `fromPromise` #48

Closed wookieb closed 1 year ago

wookieb commented 1 year ago

Idea to add 2 functions to create Either from function that might throw something and another function to create Either from promise.

https://github.com/monet/monet.js/blob/master/docs/EITHER.md#creating-an-either-from-an-exception https://github.com/monet/monet.js/blob/master/docs/EITHER.md#creating-an-either-from-a-promise

I'm happy to add it

JSMonk commented 1 year ago

I've just merged the #53, so, one part of the issue is resolved. What do you think, should we implement something like fromPromise?

JSMonk commented 1 year ago

Just added the fromPromise function too

wookieb commented 1 year ago

Amazing! Thank You so much :)

Lonli-Lokli commented 9 months ago

Just curios, what are they ways now to work with promises?

const maybeFailure = async () => { return Math.random() > 0.1 ? 42 : throw new Error('Oops') };
const doubleValue = (a: number) => a*2;

(await fromPromise(maybeFailure)) .then(eith => eith.map(doubleValue)) 

?

JSMonk commented 9 months ago

@Lonli-Lokli, I feel that you are right, smth like this:

const maybeFailure = async () => { return Math.random() > 0.1 ? 42 : throw new Error('Oops') };
const doubleValue = (a: number) => a*2;

...
// After await you can use the regular map, I believe
(await fromPromise(maybeFailure)).map(doubleValue)
// Or without parenthesis
await  fromPromise(maybeFailure)).then(x => x.map(doubleValue))

I also find the second variant less pretty, but I think the generic code with such logic could look like this:

const result = await fromPromise(maybeResult)
return result.map(doubleValue)

So, I'm not sure that I want to add a static method for each instance method to support smth like this:

await fromPromise(maybeResult).then(Either.map(doubleValue))

But I'm open for the discussion, so, if you have some arguments about it I could add static methods too.