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

315
Vistas
why it didn't catch the rejected promise?

I was wondering why the try-catch block couldn't catch the promise rejected from foo.

Frustrated, need help. Thanks in advance.

function addTask(task) {
  setTimeout(() => {
    task.resolver()
  }, 1000)
}

function foo() {
  return new Promise((resolve, reject) => {
    const task = {
      resolver: function() {
        reject('task failed')
      }
    }
    addTask(task)
  })
}

function test() {
  try {
    foo()
  } catch (e) {
    console.error(e)
  }
}

// Uncaught (in promise) task failed
test()
about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

It's the same reason that if you had:

const result = foo();

Then you would have a promise stored in result and not the settled value of the promise.

The asynchronous code is started, then the calling function continues.

Sometime later the promise is rejected, but by then it is too late for the code in test() to catch it.


If you had awaited foo(), which would require that test() be async, then it would be caught.

Otherwise you could need to use foo().catch(...).

about 4 years ago · Santiago Gelvez Denunciar

0

Promises are asynchronous but you are not awaiting. It means code continues. So you have to await or you have to use then().catch(). Something like this:

function addTask(task) {
  setTimeout(() => {
    task.resolver()
  }, 1000)
}

function foo() {
  return new Promise((resolve, reject) => {
    const task = {
      resolver: function() {
        reject('task failed')
      }
    }
    addTask(task)
  })
}

function test() {
  foo().then(console.log).catch(console.error);
}

// Uncaught (in promise) task failed
test()

about 4 years ago · Santiago Gelvez Denunciar

0

To simplify your example:

function foo() {
  return new Promise((resolve, reject) => setTimeout(reject, 1000))
}

function test() {
  try {
    foo()
  } catch (e) {
    console.error("Error");
    return;
  }
  console.log("OK!");
}

test()

will print "OK!" indeed have Node.js raise an UnhandledPromiseRejection, as that foo() invocation is just "throwing away" the promise result value. The catch() would only catch synchronous exceptions, not promise rejections.

Turning the function into async function test() and awaiting on foo() will correctly output Error and no unhandled rejection.

about 4 years ago · Santiago Gelvez 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