In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
How to achieve asynchronous programming in Node.js, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
In fact, for most developers, asynchronous programming conflicts with the linear thinking of general natural languages. So most developers can not adapt to directly event-driven programming, Node.js is the first platform to bring asynchronous programming to the application level, Node.js reveals asynchronous information all the time.
In the process of contact with Node, many people just roughly contact with a few callback functions and then give up. It is true that Node uses asynchronous programming, so it is easy to fall into callback hell, but the problem of Node asynchronous programming has been basically solved. Callback traps can be solved perfectly through event publish / subscribe mode or Promise/Defferred mode.
In fact, most developers are used to linear thinking to think about problems, so synchronous programming has always been popular. However, in the single-threaded synchronization model, CPU and I _ Pot O operations can not overlap, so the performance problem is in front of the developer. In most languages, the way to improve performance is generally solved by multithreading, but the cost of thread switching in multithreading, as well as locks and thread synchronization and other problems, so multithreading will bring trouble to the developer's business logic. On the other hand, Node directly uses asynchronous programming, which can make CPU and Imax O operate in parallel without waiting for each other, so that resources can be better utilized.
The difference between Asynchronous IO and non-blocking IO
The non-blocking IO is due to the fact that the complete IUnip O is not completed, and the immediate return is not the final data we executed, but only the current call status. In order to obtain the complete data, we need to poll and repeat the call to confirm whether the operation is complete. Asynchronous Ipicuro can realize that it does not wait for the completion of data reading, and returns immediately after performing the Icano operation. The data is written to the cache, and the underlying layer completes the monitoring operation, and returns the information of success or failure to the application.
Advantages of asynchronous programming
The biggest advantage of Node.js is the event-driven non-blocking Imax O model, which can make CPU and Imax O operations do not have to wait for each other, so that resources can be better utilized. Node.js uses a single-thread asynchronous model to solve the performance problem of blocking IMab O in the programming model, so Node.js is more suitable for Imax O-intensive problems. Because Node.js is driver-oriented programming, it needs to face a large number of requests. When massive requests act on a single thread at the same time, it is necessary to prevent any request that will consume time slices excessively. Therefore, as long as we make rational use of the asynchronous model of Node.js and the high performance of V8 engine, we can give full play to the parallel advantages of CPU and Icano.
The difficulty of Asynchronous programming
Node.js breaks through the performance bottleneck of single thread with the help of asynchronous Icano model and V8 engine, so that JavaScript embodies the practical value in the back end. But it is also because asynchronous programming will bring some difficulties to developers.
(1) function nesting is too deep
In front-end JavScript, DOM event binding is generally rare in the case of multiple event bindings. Generally, different events are bound for different DOM elements.
But for Node.js, multiple asynchronous calls can be found everywhere.
In fact, there is no problem with such a function nesting structure for the final result, but it does not take advantage of the parallelism brought by Node.js Asynchronous Imax O. And the function is too deeply nested, which will cause difficulties for the later maintenance of the developer.
(2) blocking code
In JavaScript, there is no thread sleep feature like Java's sleep (), and the only two functions that can delay operations are setInterval () and setTimeout (). So what do we do if we need to implement a delay of 1s in JavaScript? In fact, most developers may implement it like this:
But keep in mind that Node.js is a single-threaded model, so CPU resources will all serve this code at execution time. As a result, all other requests are ignored. So we can use setTimeout to rewrite the code for better results:
But there is a question, if I set the later time to 0, does it mean that the code will be executed immediately? You can think about this question. If you are interested in the answer, you can send a message directly on the official account, and I will reply in time.
(3) multithreaded programming
Because Node.js is a single-threaded model, for multi-core CPU servers, Node.js single process does not make full use of many core CPU, so browsers can separate JavaScript from UI rendering, so they can better use multi-core CPU to serve a large number of computing. However, the developers of this development mode have to face cross-thread programming, which will increase the difficulty for the single-thread programming route that JavaScript has been following.
(4) exception handling
It is actually very convenient for us to use Java for exception handling, and we can catch and handle exceptions directly through try/catch/finally statements.
However, this commonly used exception handling is not necessarily applicable in asynchronous programming, because it has been mentioned earlier that asynchronous Imax O will return immediately after submitting a request, because exceptions usually do not occur at this stage, and it will not work when you perform try/catch operations on this piece of code, because try/catch can only catch exceptions that occur in this event. The exception thrown in the callback function callback returned after the execution of the event is actually powerless, so in Node.js, the exception is returned as the first parameter of the callback function callback. If it is empty, it means that the callback function has not thrown any exception.
In the above code, if an exception occurs in the execution of checkLogin, the first parameter err of the callback function is not empty, and we can handle the exception according to this err parameter.
Asynchronous programming solution
(1) event publish / subscribe mode
(2) Promise/Deferred mode
(3) process control library
As these three schemes involve a variety of knowledge points, this article will not give a specific introduction to these three schemes for the time being, and the next article will introduce them in detail.
Asynchronous concurrency control
In Node.js, we can easily make parallel calls asynchronously, but if the concurrency is too large, our server will not be able to bear it. For example, if we make a large number of concurrent calls to the file system, the number of file descriptors in the operating system will be used up in an instant. So concurrency is easy to implement for asynchronous programming, but there must be some overload protection. Here is mainly about an overload solution: async.
Async provides a method parallelLimit () to handle the limitations of asynchronous calls.
The parallelLimit () method has a parameter to limit the number of concurrency so that only a certain number of tasks can be concurrent at the same time, but not indefinitely. In the above code, we set the number of concurrency to 1, so we can only concurrently one task at the same time.
But parallelLimit () has a drawback: it can't add parallel tasks dynamically. But async provides the queue () method to dynamically add parallel tasks, which is very efficient for operations such as traversing file directories. But the parameters received by queue () are fixed, losing the diversity of parallelLimit ().
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.