I've recently begun working with Firebase Cloud Functions, and I'm slightly confused as to how to appropriately terminate this HTTP function:
exports.UpdateUserInfo= functions.https.onRequest( async (request, response) => {
try{
//Make a read call to Realtime DB
const snapshot = await admin.database().ref('/UserData').get()
if (snapshot.exists() == false) {
response.send("No users found")
return null
}
//All of the remaining code within the scope of the try block executes
functions.logger.log("Wait, this function should have ended")
let updateUserInfo = await userInfoUpdater(response)
}
catch{
functions.logger.info(error);
response.status(500).send("ERROR")
}
})
From what I've read, the correct way to terminate an HTTP function is to send a response via the response object. However, it appears that unless I include a final call to return null, the function continues to execute beyond its intended lifespan. Even worse, the function terminates and still allows the execution of additional network calls making things quite unpredictable and unorganized (see logs). I'd like to prevent the function from continuing once the conditional is met. Is returning null the best way to ensure proper termination, or am I missing something?
CodePudding user response:
Calling response.send()
does not terminate the function immediately. It merely signals to Cloud Functions that the function should shut down after the current block of code returns, either by return statement or falling off the end of the function block. If the function doesn't return in one of these two ways, then Cloud Functions will either time out or have other problems as the CPU is clamped down soon after the response is sent.
Essentially, sending the response should be the very last thing the function does before it returns. Anything else is prone to error.