try icon indicating copy to clipboard operation
try copied to clipboard

Alternative API

Open henrycunh opened this issue 1 year ago • 0 comments

I'm glad someone released a library like this, I've been using this pattern for quite some time now, it rocks!

This issue is only a suggestion for what could be, perhaps, an alternative export with a different return signature

import { $try } from '@bdsqqq/try'

const promise = () => 
  new Promise((res) => 
    setTimeout(() => res('aha!'), 1000)
  )

const promiseThatRejects = () => 
  new Promise((_, rej) => 
    setTimeout(() => rej(new Error('oh no')), 1000)
  )

const result = await $try(promise())
if (!result.error) console.log(result.data)

const otherResult = await $try(promiseThatRejects())
if (!otherResult.error) console.log(otherResult.data)

This allows for better naming through not repeating yourself, sometimes

const fetched = await $try(fetchItems())
if (fetched.error) return handleError(fetched.error)

const transformed = await $try(transform(fetched.data))
if (transformed.error) return handleError(transformed.error)

Is less repetitive to write than

const [fetched, fetchedError] = await $try(fetchItems())
if (fetchedError) return handleError(fetchedError)

const [transformed, transformedError] = await $try(transform(fetched.data))
if (transformedError) return handleError(transformedError)

There is an argument about semantics and line width here as well, but I'm way too hungover to remember

henrycunh avatar Feb 24 '23 14:02 henrycunh