hkrlys
hkrlys

Reputation: 441

How to really terminating a function?

After reading a lot, it seems that I (as well as others) can't really figure out what really terminate a function, and when should you use it. Send, response, redirect, end, return, and a mix of them.

According to Google :

Always end an HTTP function with send(), redirect(), or end()

Now in many questions here i read that response will end your HTTP function as well.A promise will keep it awake.

I would be happy to understand which does what given this function :

 exports.server = functions.https.onRequest((request, response) => {
  1. response.status(200);
  2. response.status(200).end();
  3. return
  4. return response.redirect(someURL);
  5. sendStatus(200);
  6. response.status(200).send(dictionary)

When would you use each of this and which will terminate the function.

It's just too confusing and there is no organized document other than a few sentences saying you must terminate the function.

EDIT: Now it's even more confusing as I read here that response does not terminate the function and you can do things after your response, but you can't edit the response itself because it ended. So does response terminate the function ?? things are really not clear. Why can I execute code after "res.send"?

Upvotes: 0

Views: 90

Answers (1)

Olivier Lépine
Olivier Lépine

Reputation: 668

Since you are answering to an HTTP request, you should definitely use send() with or without status() before to send a HTTP response BUT (and you stated it) it won't stop the rest of the script to execute.

So you have to be extra careful in writing your if/then/else flow so send() can't be called multiple times.

The safest way in my opinion is also to always finish each code part with a return true or return false after calling send().

Upvotes: 1

Related Questions