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>
<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>
svelte
Example
<script>
import { tryit } from "@sveu/shared"
let result, error
function add(a, b) {
throw Error("You can't add number here")
return a + b
}
const add_async = tryit(add)
async function run() {
const data = await add_async(1, 2)
result = data?.result ?? undefined
error = data.error?.message
}
run()
</script>
{#if result}{result}{/if}
{#if error}{error}{/if}
<script>
import { tryit } from "@sveu/shared"
let result, error
function add(a, b) {
throw Error("You can't add number here")
return a + b
}
const add_async = tryit(add)
async function run() {
const data = await add_async(1, 2)
result = data?.result ?? undefined
error = data.error?.message
}
run()
</script>
{#if result}{result}{/if}
{#if error}{error}{/if}
svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Click fold/expand code
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 |