Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!