0

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

hkrlys
  • 361
  • 1
  • 13

1 Answers1

1

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

Olivier Lépine
  • 618
  • 5
  • 14
  • Thank you, not sure this answer my question. What return does? end the function or not? who is send? how is it different the response.status? and why do they say everywhere that a response will finish the function? there are too many technical words that not being covered anywhere. And for dumb people like me, it is a real mess. not clear what is send, what is response.status, and what is return. – hkrlys Oct 16 '19 at 07:35
  • Typically `return` ends a function, no code after it will be executed. if `res` is your response object, `res.send()` sends an HTTP response to the browser but this does not terminate the function. The default response status is 200 (OK). You can change this and for example, `res.status(404).send()` would send a HTTP 404 (Document not found response) – Olivier Lépine Oct 16 '19 at 20:51