Easily create nodejs server (7) : implementation of blocking operations

  • 2020-05-07 19:10:17
  • OfStack

So let's see what a blocking operation is;

I simulated an sleep() method to delay hello star printing by 10 seconds.

requestHandlers.js


function start() {
  console.log("Request handler 'start' was called.");
  function sleep(milliSeconds) {
 var startTime = new Date().getTime();
 while (new Date().getTime() < startTime + milliSeconds);
  }
  sleep(10000);
  return "Hello Start";
}
 
function upload() {
  console.log("Request handler 'upload' was called.");
  return "Hello Upload";
}
 
exports.start = start;
exports.upload = upload;

When requesting /start, it took 10 seconds to print.

When requesting /upload, it is not affected.

Next, do an experiment:

In the first entry in the address bar of the browser window http: / / localhost: 8888 / start, but do not open it!

In the second entry in the address bar of the browser window http: / / localhost: 8888 / upload, likewise, do not open it!

We press enter in the first window (" /start "), then quickly switch to the second window (" /upload ") and press enter.

Notice what happened:

/start URL took 10 seconds to load, which is exactly what we expected.

/upload URL took 10 seconds!

Yes, it doesn't have anything like sleep() in the corresponding request handler. What's the problem?

The reason is that start() contains blocking operations. Figuratively, "it blocks all other processing."

Node.js is single-threaded and can process tasks in parallel without adding additional threads.

It USES event polling (event loop) to implement parallel operations, and we should make the most of this point -- avoid blocking operations as much as possible, and use non-blocking operations more often instead.

In the next section we will show you how to implement a non-blocking operation.


Related articles: