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
Authors: Mohamed-Kaizen