Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alternative API #8

Open
henrycunh opened this issue Feb 24, 2023 · 0 comments
Open

Alternative API #8

henrycunh opened this issue Feb 24, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@henrycunh
Copy link

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

@bdsqqq bdsqqq added the enhancement New feature or request label Feb 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants