Detailed description of event-driven programming in Node. js _ node. js

Source: Internet
Author: User
This article mainly introduces Node. the event-driven programming in js is explained in detail. This article mainly describes theoretical knowledge, such as what is event-driven programming, What Is closures, and how closures help asynchronous programming, if you need it, you can refer to the traditional programming model. I/O operations are like a common local function call: The program is blocked before the function is executed and cannot continue to run. Blocking I/O originated from the earlier time slice model. In this model, each process is like an independent person, with the aim of separating everyone, in addition, you can only do one thing at a time. You must wait for the previous thing to finish before deciding what to do next thing. However, this "one user, one process" model, which is widely used on computer networks and the Internet, has poor scalability. Managing multiple processes consumes a lot of memory, and context switching also consumes a lot of resources. These are a great burden on the operating system, and as the number of processes increases, this will cause a sharp reduction in system performance.

Multithreading is an alternative. A thread is a lightweight process that shares memory with other threads in the same process. It is more like the expansion of the traditional model, it is used to concurrently execute multiple threads. When a thread waits for I/O operations, other threads can take over the CPU. When I/O operations are completed, the threads waiting in front will be awakened. That is to say, a running thread can be interrupted and then restored later. In addition, in some systems, threads can run concurrently under different cores of multi-core CPUs.

Programmers do not know the specific time at which the thread will run. They must be careful with concurrent access to the shared memory. Therefore, some synchronization primitives must be used to synchronously access a data structure, for example, a lock or semaphore is used to force a thread to execute a specific action and plan. Applications that rely heavily on the shared state between threads are prone to some strange problems that are random and hard to find.

Another way is to use multi-thread collaboration. You are responsible for explicitly releasing the CPU and handing over the CPU time to other threads, because you are responsible for controlling the thread execution plan in person, this reduces the need for synchronization, but also increases the complexity of the program and the chance of errors, and does not avoid the problems of multithreading.

What is event-driven programming?

Evnet-driven programming is a programming style in which events determine the execution process of a program. Events are handled by event handlers or event callback) event Callback is a function called when a specific event occurs. For example, the database returns the query result or the user clicks a button.

In retrospect, in the traditional congestion I/O programming mode, database queries may look like this:

The Code is as follows:


Result = query ('select * FROM posts WHERE id = 1 ');

Do_something_with (result );


The preceding query function keeps the current thread or process waiting until the underlying database completes the query and returns the result.

In the event-driven model, this query will become like this:

The Code is as follows:


Query_finished = function (result ){

Do_something_with (result );

}

Query ('select * FROM posts WHERE id = 1', query_finished );

First, you define a function called query_finished, which contains the things to be done after the query is complete. Then pass the function as a parameter to the query function. After the query is executed, query_finished is called, instead of returning the query result.

When an event you are interested in occurs, the function you define will be called instead of simply returning the result value. This programming model is called event-driven programming or asynchronous programming. This is one of the most obvious features of Node. This programming model means that the current process will not be blocked when performing I/O operations. Therefore, multiple I/O operations can be executed in parallel, after the operation is complete, the corresponding callback function will be called.

The underlying layer of event-driven programming relies on event loop. event loop is basically a structure of continuous loop calls by event detection and event processor triggering. In each loop, the event Loop Mechanism needs to detect which events occur. when an event occurs, it finds the corresponding callback function and calls it.

The event loop is only a thread running in the process. When an event occurs, the event processor can run independently without being interrupted. That is to say:

1. A maximum of one event callback function can be run at a specific time.
2. No event processor will be interrupted when running

With this, developers can stop having to worry about thread synchronization and concurrent modification of shared memory.

A well-known secret:

A long time ago, people in the system programming community knew that event-driven programming was the best way to create high-concurrency services, because it didn't have to save a lot of context, thus saving a lot of memory, there are not so many context switches, which saves a lot of execution time.

Slowly, this concept has penetrated into other platforms and communities, and some famous Event loop implementations have emerged, such as Ruby's Event machine, Perl's AnyEvnet, and Python's Twisted, in addition, there are many other implementations and languages.

To use these frameworks for development, you need to learn the framework-related knowledge and the framework-specific class libraries. For example, to enjoy the benefits of non-blocking when using Event Machine, you must avoid using synchronous class libraries. You can only use Asynchronous class libraries of Event Machine. If you use any blocking class libraries (such as most of Ruby's standard libraries), your server will lose the best scalability, because the event loop will continue to be blocked, from time to time, I/O events are blocked.

Node was initially designed as a non-blocking I/O server platform, so in general, you should expect that all the code running on it is not blocked. Because JavaScript is very small and does not force any I/O model (because it does not have a standard I/O class library), Node is built in a pure environment, there will be no historical issues.

How Node and JavaScript simplify asynchronous applications

Ryan Dahl, author of Node, initially used C to develop this project, but found that the context for maintaining function calls is too complex, resulting in high Code complexity. Then he switched to Lua, but Lua already has several blocked I/O class libraries, blocking and non-blocking mixing may confuse developers and thus impede many people from building scalable applications, so Lua is also abandoned by Dahl. Finally, he switched to JavaScript, the closure in JavaScript, and the first-level object functions. These features make JavaScript very suitable for event-driven programming. The magic of JavaScript is a major reason for the popularity of Node.

What is a closure?

A closure can be understood as a special function, but it can inherit and access the variables in the scope defined by itself. When you pass a callback function as a parameter to another function, it will be called later. What's amazing is that when this callback function is called later, it remembers the context of its own definition and the variables in the parent context, and can access them normally. This powerful feature is at the core of Node success.

The following example shows how JavaScript closures work in a Web browser. If you want to listen to a single-host event of a button, you can do this:

The Code is as follows:


Var clickCount = 0;

Document. getElementById ('myclick'). onclick = function (){

ClickCount + = 1;

Alert ("clicked" + clickCount + "times .");

};

This is the case when using jQuery:

The Code is as follows:


Var clickCount = 0;

$ ('Button # mybutton '). click (function (){

ClickedCount ++;

Alert ('clicked' + clickCount + 'times .');

});

In JavaScript, functions are the first type of objects, that is, you can pass functions as parameters to other functions. In the two examples above, the former assigns a function value to another function, the latter transfers the function as a parameter to another function, and click the event processing function (callback function) you can access every variable in the code block where the function definition is located. In this example, it can access the clickCount variable defined in its parent closure.

The clickCount variable is in the global scope (the outermost scope in JavaScript). It stores the number of times a user clicks a button. It is a bad habit to store variables in the global scope, because it is easy to conflict with other code, you should put the variables in the local scope that uses them. Most of the time, you only need to wrap the Code with one function, which is equivalent to creating another closure, so that you can easily avoid contamination of the global environment, just like this:

The Code is as follows:


(Function (){

Var clickCount = 0;

$ ('Button # mybutton '). click (function (){

ClickCount ++;

Alert ('clicked' + clickCount + 'times .');

});

}());


Note: The seventh line of the code above defines a function and calls it immediately. This is a common design pattern in JavaScript: Create a function to create a new scope.

How closures help asynchronous programming

In the event-driven programming model, first write the code to be run after an event occurs, then put the code into a function, and finally pass the function as a parameter to the caller, it will be called by the caller function later.

In JavaScript, a function is not an isolated definition. It also remembers the context of the declared scope, this mechanism allows JavaScript Functions to access all variables in the context where the function definition is located and in the parent context.

When you pass a callback function as a parameter to the caller, the function will be called at a later time. Even if the scope that defines the callback function has ended, when the callback function is called, it can still access all the variables in the ended scope and its parent scope. In the last example, the callback function is called within jQuery's click (), but it can still access the clickCount variable.

The magic of closures is shown above. Passing state variables to a function allows you to implement event-driven programming without maintaining the state. The closure mechanism of JavaScript will help you maintain them.

Summary

Event-driven programming is a programming model that determines the program execution process through event triggering. Programmers register callback functions (usually called event processors) for the events they are interested in, and then the system calls the registered event processor when an event occurs. This programming model has many advantages that traditional blocking programming models do not possess. In the past, to achieve similar features, we had to use multiple processes/multithreading.

JavaScript is a powerful language, because of its first type of object functions and closure features, it is very suitable for event-driven programming.

Related Article

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.