Home > Web Front-end > JS Tutorial > Easily create a nodejs server (7): Implementation of blocking operations_node.js

Easily create a nodejs server (7): Implementation of blocking operations_node.js

WBOY
Release: 2016-05-16 16:25:46
Original
1223 people have browsed it

Let’s take a look at what blocking operations are;

I simulate a sleep() method to delay printing of hello star for 10 seconds.

requestHandlers.js

Copy code The code is as follows:

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, there is a delay of 10 seconds before printing.

When requesting/upload, it will not be affected.

Let’s do an experiment:

Enter http://localhost:8888/start in the address bar of the first browser window, but don’t open it yet!

Enter http://localhost:8888/upload in the address bar of the second browser window. Again, don’t open it yet!

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

Attention, what happened:

The

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

The

/upload URL also took 10 seconds!

Yes, it does not have operations similar to sleep() in the corresponding request handler. What is the problem?

The reason is that start() contains blocking operations. To put it figuratively, "it blocks all other processing work."

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

It implements parallel operations through event loop. We should make full use of this - avoid blocking operations as much as possible and use non-blocking operations instead.

In the next section we will introduce how to implement non-blocking operations.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template