sodiray / radash

Functional utility library - modern, simple, typed, powerful
https://radash-docs.vercel.app
MIT License
4.18k stars 167 forks source link

Feature request - tryit sync #315

Closed stefaanMLB closed 1 year ago

stefaanMLB commented 1 year ago

Can you add a sync version of tryit ? Something like this

function tryitSync(fn: (...args: any[]) => any){
  return (...args: any[]) => {
    try{
      return [undefined, fn(...args)]
    } catch (error){
      if (error instanceof Error) return [error, undefined]
      if (['boolean', 'number', 'string'].includes(typeof error)) return [new Error(error.toString()), undefined]
      return [new Error(JSON.stringify(error)), undefined]
    }
  }
}

It would also be usefull to have to option to convert errors not of Error type into Error objects in tryit like I did in the example

stefaanMLB commented 1 year ago

I can see from the source code that you intended for tryit to work both for sync and async calls, but this isn't working correctly i.m.h.o., consider this code:

async function boot() {
  const fn = tryit((x: string) => x)
  const result = fn('test')
  console.log(isPromise(result))
  console.log(result)
  console.log(await result)
}
boot()

The result is

true
Promise { <pending> }
[ undefined, 'test' ]

ideally the return value is not a Promise when a sync function is passed.

stefaanMLB commented 1 year ago

Sorry, works fine in v11