Skip to content

Try it

Convert a function to an error-first async function.

๐ŸŽฌ Usage

<script>
    import {tryit} from "@sveu/shared"

    function add(a, b) {
        return a + b
    }

    const add_async = tryit(add)

    const {result, error} = await add_async(1, 2)

</script>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ‘ป Arguments

Name Description Type Required
fn Function to convert (...args: any[]) => any Yes

โ†ฉ๏ธ Returns

Name Description Type
result Result of the function any
error Error thrown by the function Error

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import type { FunctionArgs } from "../utils"

/**
 * Convert a function to an error-first async function.
 *
 * @param fn - A function to be converted to an error-first async function.
 *
 * @see https://radash-docs.vercel.app/docs/async/tryit
 *
 * @returns An error-first async function.
 *
 */
export function tryit(fn: FunctionArgs) {
    return async (...args: any) => {
        try {
            return { result: await fn(...args), error: null }
        } catch (err) {
            return { result: null, error: err }
        }
    }
}

Last update: 2023-02-09