DEV Community 👩‍💻👨‍💻

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

kevinleebuchan profile image

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.

joelbonetr profile image
JoelBonetR Author • Edited on

😂 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) =>
    .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(''));

  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! 😁