In-depth understanding of node. JS Asynchronous Programming

Source: Internet
Author: User
Tags emit

Tag: Log has a message current calculation process operation self Wife HTML

1. Overview The hottest technology in the open source community is the node. js, a server-side programming technology and platform that uses JavaScript as the main development language, is destined to be a big start. Certainly can attract the public eye, certainly not the sanjiaojiuliu, must have the unique superiority and the charm, can cause the group ape to chase. In this paper, the asynchronous IO and event programming model of node. JS is an in-depth analysis of asynchronous IO and events programming. # #2. What is asynchronous synchronous and asynchronous is a relatively early concept, presumably when the operating system is invented should appear. To give a simple example of life, such as sending text messages will be better to explain their differences: synchronization: Is in the bitter force of the state of my, but the dog luck to the girlfriend and is in a love period, so send a text message to her to inquire about the restaurant to eat, impatient looking at the phone waiting for SMS reply, Receive information to see if you are working overtime or off duty; Async: In the company's operational decision-making critical work status of you, can not be interrupted for too long, casually sent a question to ask the wife when to cook dinner and then immediately return to work, while working while waiting for SMS reply notification, according to the notice to decide whether to work and off duty. As you can see, the characteristics of synchronization and Asynchrony are:

Need collaboration between at least two objects (boyfriends and girlfriends, husbands and wives);

Two objects need to handle a range of things (work and eat). Another similar example of CPU calculation and disk operation: synchronization: The CPU needs to calculate 10 data, after each result, write it to disk, wait for the write to succeed, then calculate the next data until it is complete. Async: The CPU needs to calculate 10 data, each calculated a result, write it to disk, do not wait for the result of the success of the write, immediately return to continue to calculate the next data, the calculation process can receive the success of the previous write notification until completed.

# #3. Why do you need to know it asynchronously, and why, the reader may ask, why is there asynchronous? According to the above text message and disk operation example, the answer is obvious, in order to improve efficiency, CPU computing speed and disk read and write speed is too far, the disk is in short supply, so there is a computer storage system layered design , balancing efficiency and cost. It can be said that laziness drives human progress, and that any method that reduces the amount of time it takes to achieve the same effect will certainly be prioritized. When sending a text message waiting for the other party to reply the time is purely wasted, the CPU to write to the disk waiting for the results of the waiting time is also ruthlessly consumed, this is a time to pay attention to efficiency is completely unbearable, so that employees have been in a busy state, the maximum amount of staff to extract value is the Boss pursuit, It is also efficient to keep the CPU and the disk running at full load to handle the transaction. Therefore, asynchronous processing has occurred.

# #4. node. js asynchronous Io and event first contact with node. js, I'm afraid anyone will be instilled first. node. JS is different: Asynchronous IO and event-driven. There is no doubt that this is indeed the most fascinating feature of node. js, and this is where this article focuses its analysis. # # #4.1 Because of the high efficiency of asynchronous node. js, the node. JS design was designed to be an efficient Web server, with the author taking the async mechanism into account throughout the node. JS programming model, and novice programming with node. JS is often tied to the habit of other programming languages, such as C /c++, feel at a loss. We can peep out their differences from the following section of a simple Sleep program code, the following is a 10-time C code printed from the Linux program:

#include

#include

#include

int main ()

{

int i;

time_t the_time;

for (i = 1; i <=; i++) {

The_time = Time ((time_t *) 0);

printf ("The Time is%ld\n", the_time);

Sleep (2);

}

Exit (0);

}

The results are printed as follows: The time is 1396492137 the time is 1396492139 the time is 1396492141 the time is 1396492143 the time is 1396492 145 The time is 1396492147 the time was 1396492149 the time is 1396492151 the time was 1396492153 the time is 1396492155 from C Printed results can be found, is printed every 2 seconds, according to the C program of the logic, the code line-by-row execution. The following node. JS code is intended to be like the C code above, with the purpose of printing a time interval of 2 seconds, a total of 10 prints (the programmer who first came in contact with node. js from C + + might write the following code):

function Test () {

for (var i = 0; i < i++) {

Console.log (new Date);

SetTimeout (function () {}, 2000); Sleep for 2 seconds before you print the next for loop

}

};

Test ();

Print Result: Tue Apr 14:53:22 gmt+0800 (China Standard Time)

Tue APR 14:53:22 gmt+0800 (China Standard Time)

Tue APR 14:53:22 gmt+0800 (China Standard Time)

Tue APR 14:53:22 gmt+0800 (China Standard Time)

Tue APR 14:53:22 gmt+0800 (China Standard Time)

Tue APR 14:53:22 gmt+0800 (China Standard Time)

Tue APR 14:53:22 gmt+0800 (China Standard Time)

Tue APR 14:53:22 gmt+0800 (China Standard Time)

Tue APR 14:53:22 gmt+0800 (China Standard Time)

Tue APR 14:53:22 gmt+0800 (China Standard Time)

The findings are printed at 14:53:22 at the same point in time, and there is no sleep for 2 seconds before performing the next round of cycle printing! What is this? From the official documentation we see that settimeout is the second parameter that represents the callback function after the elapsed time in the execution of the first argument. So we can analyze that because of the asynchronous mechanism of node. js, after each for loop, settimeout registers a callback function that executes after 2 seconds and then immediately returns to execute Console.log (new Date), causing all the printing time to be the same point. So we modify the code for the For loop as follows:

for (var i = 0; i < i++) {

SetTimeout (function () {

Console.log (new Date);

}, 2000);

}

The execution results are as follows: Thu APR 09:30:35 gmt+0800 (China Standard Time)

Thu APR 09:30:35 gmt+0800 (China Standard Time)

Thu APR 09:30:35 gmt+0800 (China Standard Time)

Thu APR 09:30:35 gmt+0800 (China Standard Time)

Thu APR 09:30:35 gmt+0800 (China Standard Time)

Thu APR 09:30:35 gmt+0800 (China Standard Time)

Thu APR 09:30:35 gmt+0800 (China Standard Time)

Thu APR 09:30:35 gmt+0800 (China Standard Time)

Thu APR 09:30:35 gmt+0800 (China Standard Time)

Thu APR 09:30:35 gmt+0800 (China Standard Time) magical, still the same time point, damn! Calm down analysis, always consider the asynchronous, the for loop every time the SetTimeout register 2 seconds after the execution of a print time callback function, It then returns immediately, executes the settimeout, and repeats until the for loop ends, because execution is too fast, resulting in a callback function that is executed after 10 2 seconds at the same point in time, resulting in an immediate execution of all the callback functions after 2 seconds. We add Console.log before the For loop ("before for:" + new date) and then Console.log ("After for:" + new Date) To verify our speculation that the results are as follows (omit 8 identical print lines) : Before For:thu Apr 09:42:43 gmt+0800 (China Standard Time)

After For:thu Apr 09:42:43 gmt+0800 (China Standard Time)

Thu APR 09:42:45 gmt+0800 (China Standard Time)

Thu APR 09:42:45 gmt+0800 (China Standard Time) ... (Omitting the same print line as the previous line 8) can then peek out of the node. JS asynchronous mechanism, the code in the for loop after the code in almost a unit of seconds to complete, and the callback function in the timer is required after 2 seconds to execute, but also in the same second execution completed. So how to achieve the original C language every 2 seconds to print a system time requirement function, I implemented the following a wsleep function, placed in the For loop, can achieve this purpose:

function Wsleep (millisecond) {

var startTime = new Date (). GetTime ();

while (new Date (). GetTime () <= millisecond + startTime) {

}

}

But the function has a flaw that makes it impossible for him to use in the project, excuse me. # # #4.2 node. JS Event Programming Event programming is not a new concept, the program of Interface UI programming apes can feel familiar with events, especially client development and web development, such as Android, iOS, Or the programmers of JavaScript front-end programming, a button, a list item, a long press operation, and so on, each time it is pressed by the operating system or browser to generate an event, you need to do is to write and register the event's callback function (may not be called in the domain of the callback function, But from the perspective of the operating system is actually a callback function, when this event occurs, execute your callback function. When node. JS is different, its genes are made up of events and Asynchrony. Looking at a fragment of the real project code used in the production environment (omitting some irrelevant code), I add a note about the event information to make the reader clearer:

Self.sio.sockets.on (' Connection ', function (socket) {//Listen for socket connection event

var addr = socket.handshake.address;

var limiter = new Ratelimiter (constant. Rl_maxreqratelimit, Constant. Rl_ratelimitunit, True);

var connect = new Connection (socket);

Then (function (defer) {

if (iplimit) {

Throttle.throttlehandle (connect, null, defer); Result callback Handling Event

} else {

Defer (null); Send processing result Event

}

}). All (function (defer) {//Receive processing result event

Socket.on (' message ', function (data) {//Listen for data transfer event

Cloudkeymain (Connect, 1, data, CLOUDKEYAPI);

});

});

Socket.on ("Disconnect", function (data) {//Monitor socket offline event

var currentsockclient = connect.client;

if (currentsockclient) {

Currentsockclient.signaloffline (); Sending client Offline events

}

});

});

From the above code, we can see the ubiquitous event mechanism of node. JS, the event mechanism lets us focus on the process of code business, improve the efficiency of software development, reduce the coupling between http://www.chinamaofa.com/code, let people not be entangled with trivial, Programming is more interesting. How to start a simple node. JS event Programming, the answer is to use node. js JavaScript API Core Module events of the Events.eventemitter class can be completed, the following with a QQ online and offline to explain, the use of the event mechanism mainly includes 3 aspects of the content:

Inherit events. Eventemitter event class, is mainly the implementation of the shielding event mechanism (in fact, the principle is very simple), let us directly use;

The registration of the event;

The publication of the event.

var events = require (' events ');

var util = require (' util ');

function Myqq () {

Events. Eventemitter.call (this);

......

}

Util.inherits (MYQQ, events. Eventemitter);

OK, the above code to complete the event mechanism to add, at this time, our work for the QQ Add Event Registration function for event registration, event registration is mainly the use of Eventemitter http://www.sansewa.com/zhifa_anli/toufa/ 2018-08-24/816.htmlon () completes, because we inherit eventemitter, we can use the on function directly, we customize the processing business in the second parameter callback function of the on function, and register our own on-line event, The following is a QQ on-line when the simple processing business:

function Onlinehandle (qqnumber) {

Get and Qqnumber a list of contacts

Get offline messages

......

}

var myqq = new Myqq ();

Myqq.on ("OnLine", Onlinehandle);

The above code completes the handling of the event, when it is time to publish the event, and the following business scenario may be the one that needs to publish the event, with the emit () function of the release event:

function Main () {

Connecting to a server

Detecting Login Status

Post an event when the logon server succeeds

Myqq.emit ("OnLine", 123655245);

}

After the Myqq.emit () function is executed and the online event is published, the Onlinehandle () function is immediately executed to handle our registered business logic, and it is important to note that Event Publishing function emit the number of arguments after the second parameter needs to be the same as the number of processing function parameters we registered, and the order is consistent to handle correctly, why is there such a requirement? This needs to be said from the principle of node. JS events.

In-depth understanding of node. JS Asynchronous Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.