DEV Community

Discussion on: Which functions/methods do you...

Collapse
 
c_basso profile image
Vladimir Ivakhnenko

Function for prevent using try catch in all async await calls

type Result<DataType> = [
    Error | undefined,
    DataType | undefined
];

export const to = <DataType = any>(
    promise: Promise<DataType>
): Promise<Result<DataType>> => promise
    .then((data) => ([undefined, data]) as Result<DataType>)
    .catch((err: Error) => ([err, undefined]) as Result<DataType>);

Enter fullscreen mode Exit fullscreen mode

and use it like this

const [data, error] = await to(fetchData());

if (error) {
   console.error(error);
   return;
}

console.log(data);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kevinleebuchan profile image
KevinLeeBuchan

You should do a post on this. I use JavaScript all the time but I'm seeing syntax I'm not familiar with. I feel like I'm peeking through a window from a room I didn't know I was stuck in.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

😂 Both @c_basso and @fedyk solutions are coded in TS that can be the cause of your confusion @kevinleebuchan, here's a JS translation (guys correct me if I miss something)

/**
 * Handles promise resolution
 * @param {Promise} promise
 * @returns {any}
 */
export const go = (promise) =>
  Promise.resolve(promise)
    .then((result) => [result, null])
    .catch((error) => [null, error]);
Enter fullscreen mode Exit fullscreen mode

Usage example:

/** Retrieves Ditto data */
const getDitto = async () => {
  const [result, error] = await go(fetch('https://pokeapi.co/api/v2/pokemon/ditto'));

  if (error) console.error(error);
  else console.log(await result.json());
};

await getDitto();
Enter fullscreen mode Exit fullscreen mode

Note that the return value of the go function is always an array with two positions, the first one intended to be a successful result, the second one reserved for the error so in case it succeeds it sends [result, null] and in case it fails it sends back [null, error], this may help to understanding:

const [result, error] = ['Success!', null];

result; // 'Success!'
error; // null
Enter fullscreen mode Exit fullscreen mode

Hope it helps! 😁

Collapse
 
fedyk profile image
Andrii Fedyk

to - funny name. I use similar helper, but I call it go. Here my recent post about it dev.to/fedyk/golang-errors-handing...

function go<T>(promise: T) {
  return Promise.resolve(promise)
    .then(result => [null, result] as const)
    .catch(err => [err, null] as const)
}
Enter fullscreen mode Exit fullscreen mode