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

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

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