简体   繁体   中英

NodeJS working with variables and concurrent connections

I'm trying to wrap my head around how javascript and nodejs work with concurrent connections.

Consider the following minimal example:

var app = express();
var i = 0;

app.get("/", function(req, res) {

    if (i < 10){
         doSomething();
         i++;
    }else{
         doDefault();
    }

    res.render("test");
}

The following code does doSomething() if you visit the page 10 times, but then does doDefault() for subsequent requests.

Could it be possible that doSomething() is run 11 or more times? Because multiple concurrent requests to the server could evaluate i<10 to be true, but requests do i++ at the same time?

What happens if doSomething() reads a file locally on the server, this request would happen concurrently in javascript (with callbacks or promises as this is the node way of doing things) and still continue to execute. Would it then be safe to do this instead:

if (i < 10){
    i++;
    doSomething();
}

Would I now be guaranteed the function doSomething() would run exactly 10 times even if thousands of requests hit the server at the same time?

This is where asynchronous natures comes in. Even though you made parallel request to NodeJS, however request come one by one to server. And all is synchronous by default in Javascript means next request could only be processed after the first one. So if your API includes blocking code which takes 5 min then your next request will be executed after 5 min even though arrived at same time.

In your example doSomething() can be synchronous or asynchronous, it doesn't affect the synchronous flow and will i++ before accepting next request.

To simulate you can try a big for loop and see when next API call is responded to.

var app = express();
var i = 0;

app.get("/", function(req, res) {
  console.log('request received i = ', i);

  for(let j = 0; j<9999999999999; j++) {}

  i++;
  res.render("test");
}

if you want to execute all parallel request even for i>10 just increment i after some asynchronous function.

app.get("/", function(req, res) {
  console.log('request received i = ', i);

  if (i<10) {
    setTimeout(function(){
      i++;
    },5000);
  } else {
    doSomethingElse();
  }
  res.render("test");
}

Any number of request received within 5 seconds of first request, will be executed as i value is not incremented and will be incremented after asynchronous work of 5 seconds. This is logic for asynchronous and event loop.

Do check this out for more over event loop .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM