Skip to content

tryit

Convert a function to an error-first function

240 bytes

Usage

Error-first callbacks were cool. Using mutable variables to hoist state when doing try/catch was not cool.

The tryit function let’s you wrap a function to convert it to an error-first function. Works for both async and sync functions.

import * as
import _
_
from 'radashi'
const
const api: {
users: {
find: (id: number) => Promise<any>;
throw: Error;
};
}
api
= {
users: {
find: (id: number) => Promise<any>;
throw: Error;
}
users
: {
find: (id: number) => Promise<any>
find
: async (
id: number
id
: number) =>
id: number
id
< 3 ? {
id: number
id
,
name: string
name
: 'Alice' } :
throw: Error
throw
new
var Error: ErrorConstructor
new (message?: string) => Error
Error
('Not found'),
},
}
const
const userIdA: 1
userIdA
= 1
const
const userIdB: 3
userIdB
= 3
const [
const errA: Error | undefined
errA
,
const userA: any
userA
] = await
import _
_
.
tryit<[id: number], Promise<any>, Error>(func: (id: number) => Promise<any>): (id: number) => _.ResultPromise<any, Error>
export tryit

A helper to try an async function without forking the control flow. Returns an error-first callback-like array response as [Error, result]

tryit
(
const api: {
users: {
find: (id: number) => Promise<any>;
throw: Error;
};
}
api
.
users: {
find: (id: number) => Promise<any>;
throw: Error;
}
users
.
find: (id: number) => Promise<any>
find
)(
const userIdA: 1
userIdA
) // [null, { id: 1, name: 'Alice' }]
const [
const errB: Error | undefined
errB
,
const userB: any
userB
] = await
import _
_
.
tryit<[id: number], Promise<any>, Error>(func: (id: number) => Promise<any>): (id: number) => _.ResultPromise<any, Error>
export tryit

A helper to try an async function without forking the control flow. Returns an error-first callback-like array response as [Error, result]

tryit
(
const api: {
users: {
find: (id: number) => Promise<any>;
throw: Error;
};
}
api
.
users: {
find: (id: number) => Promise<any>;
throw: Error;
}
users
.
find: (id: number) => Promise<any>
find
)(
const userIdB: 3
userIdB
) // [Error('Not found'), undefined]

Currying

You can curry tryit if you like.

import * as
import _
_
from 'radashi'
const
const findUser: (id: number) => _.ResultPromise<any, Error>
findUser
=
import _
_
.
tryit<[id: number], Promise<any>, Error>(func: (id: number) => Promise<any>): (id: number) => _.ResultPromise<any, Error>
export tryit

A helper to try an async function without forking the control flow. Returns an error-first callback-like array response as [Error, result]

tryit
(
const api: {
users: {
find: (id: number) => Promise<any>;
throw: Error;
};
}
api
.
users: {
find: (id: number) => Promise<any>;
throw: Error;
}
users
.
find: (id: number) => Promise<any>
find
)
const [
const err: Error | undefined
err
,
const user: any
user
] = await
const findUser: (id: number) => _.ResultPromise<any, Error>
findUser
(
const userId: 1
userId
)