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 _ from 'radashi'
const api = {
users: {
find: async (id: number) => id < 3 ? { id, name: 'Alice' } : throw new Error('Not found'),
},
}
const userIdA = 1
const userIdB = 3
const [err, user] = await _.tryit(api.users.find)(userId) // [null, { id: 1, name: 'Alice' }]
const [err, user] = await _.tryit(api.users.find)(userIdB) // [Error('Not found'), undefined]

Currying

You can curry tryit if you like.

import * as _ from 'radashi'
const findUser = _.tryit(api.users.find)
const [err, user] = await findUser(userId)