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

137
Views
How do I handle res.status(<code>).send() in async functions?

I've seen many different ways of handling res.status(<code>).send(<whatever>) especially when it comes to async functions, and I'm not sure which one is right. Can someone provide an explanation for the appropriate way to do it?

export const randomFunction = functions.runWith(functionDefault).https.onRequest(async (req, res) => {
    functionSecurity.setHttpSecurityHeaders(res);

    if (req.body.automaticFail) {
        res.status(500).send(`This function automatically bombed out`);
        return Promise.reject();
    }
    
    res.status(200).send(`This function automatically succeeded`);
    return Promise.resolve(200);
}

export const randomFunction2 = functions.runWith(functionDefault).https.onRequest(async (req, res) => {
    functionSecurity.setHttpSecurityHeaders(res);

    if (req.body.automaticFail) {
        return res.status(500).send(`This function automatically bombed out`);
    }
    
    return res.status(200).send(`This function automatically succeeded`);
}

export const randomFunction3 = functions.runWith(functionDefault).https.onRequest(async (req, res) => {
    functionSecurity.setHttpSecurityHeaders(res);

    if (req.body.automaticFail) {
        res.status(500).send(`This function automatically bombed out`);
    }
    
    res.status(200).send(`This function automatically succeeded`);
}

Perhaps even none of these are correct? I'm just confused onw how asyncronous operations are supposed to work.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

randomFunction2 will work perfectly, the reason is that Node.js will end the request-response cycle after calling the send() function so you don't have to worry whether it is async or not.

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!