Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda