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

feature: Add a chainP, andThen or similar to simplify work with promises/async await #20

Open
hrajchert opened this issue May 16, 2019 · 0 comments

Comments

@hrajchert
Copy link
Contributor

Probably something in these lines:

type ChainPFn <A, B> = (a: A) => Promise<B>;

const chainP = <A, B, E = UnknownError>(fn: ChainPFn<A, B>, handler?: (err: unknown) => E) =>
    chain(
         // TODO: need to wrap fn inside a try catch
        (a: A) => Task.fromPromise(fn(a))
            .catch(err => {
                if (handler) {
                    return Task.reject(handler(err));
                } else {
                    return Task.reject(new UnknownError(err) as any as E);
                }
            })
    )
;

This can allow something like

async function foo (n: number) {
    if (n === 1) {
        throw 'Buu';
    }
    return n;
}
// If the function fails then the error is wrapped in UnknownError
Task.resolve(1).pipe(
    chainP(val => foo(val))
); // Task<number, UnknownError>

// If you provide a handler you can control the type of error
Task.resolve(1).pipe(
    chainP(val => foo(val), err => err as string)
); // Task<number, UnknownError | string>
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

1 participant