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

312
Visualizações
How is the error from a promise being caught inside resolve()?

This is what my code looks like:

  userUpdate(req: Request, res: Response) {
    this.userTaskObj.userUpdate(req.params.id, req.body).then(() => {
      res.status(200).json({
        status: 'OK',
        message: 'User updated',
      });
    })
      .catch((err) => ErrorHandler.getErrorMessage('User', res, err));
  }

(below function is inside UserTask class)

  userUpdate(id: string, data: any) {
    let query: Promise<any>;
    if (data.provides) {
      query = User.findByIdAndUpdate(id, {$addToSet: {provides: data.provides}}).exec();
    } else {
      query = User.findByIdAndUpdate(id, data).exec();
    }
    return new Promise((resolve, reject) => {
      resolve(query);
      // query.then(res => resolve(res))
      // .catch(err => reject(err));
    });
  }

I thought I wouldn't able to catch errors from the query using resolve alone. But it does catch mongoose errors. When I replaced it with the commented part, that too works but the errors are caught inside the catch() which is rejected. How is the code catching errors without the catch() ?

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

0

.catch() runs when the promise is rejected. An error results in rejecting the promise. As a consequence:

(new Promise(()=>{throw Error()}).then(()=>{
  console.log("this will not display because the promise was rejected beforehand")
}))
.catch(()=>{
  console.log("this will run");
})

In your case, when the mangoose error occurs, this.userTaskObj.userUpdate(req.params.id, req.body) has already returned, and the returned object is a promise instance.

This promise instance fails to resolve according to the query failure, so it is eventually rejected. Indeed, Promise.resolve(Promise.reject()) results in a rejected promise [Note: as commented by others, this is anti-pattern].

Hence the .catch() takes over.

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