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

147
Visualizações
Respond from controller method without express response

I'm trying to respond in case a fetch for an item doesn't return something from another method that doesn't have the express response. I call this method from another that if it has the express response:

const updateItem = async (req, res = response ) => {

    const id = req.params.id;
    const idItem = req.params.idItem; 

    await itemExists( id, idItem);

...

And in the itemExists() function I search for the item in mongo and if it doesn't exist I want to send it as a response but I don't know how to do it without using Express response:

const itemExists = async ( id, idItem ) => {

    const item = await PettyCashItems.findOne({ _id: id, "items._id": idItem });

    if (!item) {
        return ......
    }
}

Thanks.

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

0

As already mentioned by one of the comments, there's no way to use response object without having access to it.

However, what you want can be achieved in two ways:

1- Easy way - return a value from itemExists function and send the response according to returned value from itemExists

const updateItem = async (req, res = response ) => {

    const id = req.params.id;
    const idItem = req.params.idItem; 

    const exists = await itemExists( id, idItem);

    if (exists) {
      res.send('YES')
      return;
    }

    res.send('NO');
}

2- Better way - Setup error handling for your express application so all thrown error are caught and response is sent based on the thrown error, then you can simply

class BaseHTTPException extends Error {
  constructor(statusCode) {
    super();
    this.statusCode = statusCode;
  }

}


class ItemDoesNotExistException extends BaseHTTPException {
  constructor() {
    super(400)
  }
}

throw new ItemDoesNotExistException()

in your itemExists function.

Further reading: https://expressjs.com/en/guide/error-handling.html

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