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

179
Visualizações
Why can't function A catch the error thrown by function B

I'm doing try and catch exercises in JavaScript.

here is my code

function getTime1() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(11111);
    }, 1000);
  });
}

function getTime2() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(22222);
    }, 1000);
  });
}

async function funB() {
  // try {
  let b = await getTime2();
  throw "B error";
  // } catch (e) {
  //   console.log("this" + e);
  // }
}

async function funA() {
  try {
    let a = await getTime1();
    funB();
  } catch (e) {
    console.log("that" + e);
  }
}
funA();

and here is the result

Uncaught (in promise) B error

I want to know why there is no catch in funb and Funa. Thank you

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

From my understanding try/catch doesn't work with async :

"Because errorTest is async, it will always return a promise and will never begin execution exactly where you call it: it is asynchronous. errorTest returns, and you exit the try block, before a single line of code within errorTest is run. Therefore, your catch block will never fire, because nothing in errorTest would synchronously throw an exception."

Source : Why is try {} .. catch() not working with async/await function?

Since async will return a Promise, I believe you'll need to use the catch on the Promise itself

funB().then((result) => {
    console.log(result);
}).catch((error) => {
    console.error(error);
});
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