Skip to content

go

Static Badge

This function mimics the Go language's error handling style, Executing a function (async or regular) and returning a fulfilled Promise with value of a tuple of [Awaited<result>, null] on success or [null, error] on failure.

Added in v0.0.4

Usage

ts
import { go } from 'parsnip-kit'

function getUltraAnswer() {
  return Promise(resolve => setTimeout(resolve, 750))
}
const [result0, error0] = await go(getUltraAnswer)
// [42, null]
if (error0 !== null) {
  // do something...
}

function throwErrorExample() {
  throw new Error('test')
}
const [result1, error1] = await go(throwErrorExample)
// [null, Error: test]

API

Type Parameter

ArgTypeDescription
TThe type of the function's return value
U= anyThe type of the error (defaults to any)

Arguments

ArgTypeOptionalDefaultDescription
func(...x: any[]) => TfalseundefinedThe function to execute.

Returns

Type
Promise<[T, null] | [null, U]>