Feel free to correct me if this question has already been asked. (I've done as much research as I can handle before asking)
I'm really trying to wrap my head around the life cycle of request and response objects.
Take a look at the following code snippet:
app.get('/', function(req, res) {
var setCookie = function(err, idCookie) { //callback after cookieSearch in DB
// ... do something with the result of findCookieInDatabase() (handle error, etc.);
res.sendfile('index.html');
}
var cookie = parseCookie(req.get('Cookie')); //parse and format cookie
findCookieInDatabase(cookie, afterCookieSearch); //tries to find cookie is DB
// .. do some content return stuff, etc.
}
(Please be aware that the actual code does much more, including checking if 'Cookie' even exists etc.)
I know that req and res objects are created and eventually have to be garbage collected. (At least I hope so)
When findCookieInDatabase() is called with setCookie as an argument, I understand that setCookie is just a string (containing the function) until the callback(setCookie) statement is reached in findCookieInDatabase().
I also realize that I could be completely mistaken in my assumption above, which might be due to my lack of understanding of javascript callbacks. (I've searched extensively on this topic but only found endless tutorials on how to use callbacks, nothing about what goes on behind the scenes)
So here's my question: How does javascript (or node.js) determine how long to keep 'res' alive and when it's safe to garbage collect it?
Does the line res.sendfile in setCookie serve as an active reference because it's invoked through findCookieInDatabase()?
Does javascript actually monitor all references and keep req and/or res alive for as long as any part of any callbacks or other functions are still running?
Any assistance would be greatly appreciated. Thank you for reading.