Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
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.

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda