Proposal: `fromTry` and `fromPromise`
wookieb opened this issue · 5 comments
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
I've just merged the #53, so, one part of the issue is resolved.
What do you think, should we implement something like fromPromise
?
Just added the fromPromise
function too
Amazing! Thank You so much :)
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))
?
@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.