Strange behavior implementing long polling in NODE.JS

I have this node.js code to implement a “long poll”:

var lpres1; // store the response object globally

// accept long poll call that will block until released by lp_free1 call
app.get('/API/lp1', (req, res) => {
  lpres1 = res;  // store response object so we can respond later
 
});

// free up long poll call response and also send the response to this call
app.get('/API/lp_free1', (req, res) => {

  lpres1.setHeader("Access-Control-Allow-Origin", "*");
  lpres1.setHeader("Content-Type", "application/json"); 
  lpres1.status(200).send("OK from LP1").end();


  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Content-Type", "application/json"); 
  res.status(200).send("OK").end();


});
  • I open two browser tabs
  • In the first I call “localhost:8080/API/lp1” and the browser blocks (as expected)
  • In the second tab I call “localhost:8080/API/lp_free1” and the response in browser one returns “OK from LP1” and the second browser “OK”. This is all as expected: happy days.

where I see strange behavior:

  • I open three browser tabs
  • In the first I call “localhost:8080/API/lp1” and the browser blocks (as expected)
  • In the second I call “localhost:8080/API/lp1” and the browser blocks (here I expect the global variable lpres1 to be overwritten by this call and would lose the ability to respond to the first call – but no!)
  • In the third tab I call “localhost:8080/API/lp_free1” and the response in browser one returns “OK from LP1”. I expected browser two to return
  • THEN I make the call in browser three again to lp_free1. This time browser two returns! As there is only one global variable I am using, how is node.js magically able to respond to the other browser??

Read more here: Source link