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

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

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 Relatório

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 Relatório

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