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

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

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