Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Refactoring – Destructuring data from async function result or fallback value

I have an async function that might fails:

const f = () => new Promise((_, reject) => reject("Ups"));

and a FALLBACK value constant:

const FALLBACK = { name: "Raul" };

I am trying to destructure the name field from the f() method response data, (as, if it doesn’t fail, the return will be an object with this field), and in case that it fails, I use the fallback value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am doing the following:

function f() {
  return new Promise((_, r) => r("Ups"));
}

const FALLBACK = { name: "Raul" };

(async () => {
  const { name } = (await f().catch(() => {})) ?? FALLBACK; // I need to refactor this line

  console.log(name);
})();

How can I refactor this code?

>Solution :

It seems that you just want await f().catch(() => FALLBACK). If f() rejects, then you’ll substitute the FALLBACK object as the result

Here’s a working example:

function f() {
  return new Promise((_, r) => r("Ups"));
}
const FALLBACK = { name: "Raul" };

(async () => {
  const { name } = await f().catch(() => FALLBACK); 

  console.log(name);
})();

Some will not like the mixing of .catch() and await and suggest using try/catch instead of .catch(). Either will work – that’s a style preference. In this particular situation, I find .catch() to be simpler looking – but follow your own preference.

Also, note that I removed the async from the f() definition. Since you’re not using any of the features of an async function, it is not necessary or useful.

And, note that it is sometimes dangerous to blindly .catch() all possible errors without even logging the error. Something as simple as a typing error upstream may cause this .catch() to trigger and you will be quite confused why your code is suddenly doing what it’s doing (because you’re silently eating an error you probably didn’t intend to eat and you should at least be logging).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading