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