Home > database >  Javascript Refactoring - Destructuring data from async function result or fallback value
Javascript Refactoring - Destructuring data from async function result or fallback value

Time:11-18

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.

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);
})();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

How can I refactor this code?

CodePudding user response:

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);
})();
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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).

  • Related