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

192
Vistas
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 Respuestas
Responde la pregunta

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