Skip to content

Instantly share code, notes, and snippets.

@jonasgeiler
Last active December 25, 2023 16:24
Show Gist options
  • Save jonasgeiler/6254bb2bbcfb8da1117b75d2e485cbaa to your computer and use it in GitHub Desktop.
Save jonasgeiler/6254bb2bbcfb8da1117b75d2e485cbaa to your computer and use it in GitHub Desktop.
A small try/catch alternative utility function that simplifies error handling with promises (works a bit like Rust's error handling)
export const jab = <T>(v: T) => Promise.allSettled([ v ]).then(([ r ]) => r)
@jonasgeiler
Copy link
Author

jonasgeiler commented Dec 25, 2023

Usage

import { jab } from './jab'
import { getUser } from './api'

const res = await jab(getUser('test'))
if (res.status === 'fulfilled') {
	console.log(res.value) // User
} else {
	console.error(res.reason) // Error
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment