Details about the node event notification mechanism in node. js

Source: Internet
Author: User
Tags emit exception handling require


Difficulties in asynchronous programming

Nodejs makes asynchronous programming so popular, which is also the first large-scale emergence of asynchronous programming at the business level. it uses the asynchronous I/O model and V8 high-performance engine to break through the performance bottleneck of a single thread, so that javascript can be used at the backend. on the other hand, it also unifies the programming model of front-end javascript. developers may feel the freshness and discomfort of asynchronous programming to varying degrees. next, sort out the difficulties in asynchronous programming according to @ Park Ling's deep dive into nodejs:

Difficulty 1: Exception handling
Usually, the browser uses try/catch/final block to capture and handle exceptions:

Try {
Dosomething ();
} Catch (e ){
Docatch ();
}
But this is not necessarily practical for asynchronous programming. asynchronous I/O implementation involves two phases: request submission and processing result. the two phases have event-Loop scheduling, and they are not associated with each other:

Var asnyc = function (callback ){
Process. nextTick (callback );
};
After async () is called, callback is stored until the next event loop (tick) is retrieved for execution. try/catch operations on asynchronous methods can only capture exceptions in the current event loop. exceptions thrown during callback execution are powerless:

Try {
Async (callback );
} Catch (e ){
Docatch ();
}
Example of another error:

Try {
Req. body = JSON. parse (buf, options. reviver );
Callback (); // This is written to capture exceptions and still execute the callback. However, if an exception exists in the callback, the callback will be executed twice.
} Catch (e ){
Err. body = buf;
Err. status = 400;
Callback (err );
}
Difficulty 2: function nesting is too deep
Var class = require ('./module/class ');
Export. pageStudent = function (req, res ){
Var rtnJson = {};
Class. getStudent ('class 1 ', function (error, oneResult ){
If (! Error & oneResult ){
RtnJson ['class 1 '] = oneResult;
Class. getStudent ('class 2 ', function (error, twoResult ){
If (! Error & twoResult ){
RtnJson ['2 class'] = twoResult;
Class. getStudent ('class 3 ', function (error, threeResult ){
If (! Error & threeResult ){
RtnJson ['3 class'] = threeResult;
// All three classes are obtained
Res. render ('./veiw/pageStudent', {students: rtnJson });
} Else {
Res. render ('./veiw/pageStudent', {students: rtnJson });
                        }
});
} Else {
Res. render ('./veiw/pageStudent', {students: rtnJson });
                }
});
} Else {
Res. render ('./veiw/pageStudent', {students: rtnJson });
        }
});
}
Some people with code cleanliness may find it unacceptable.

Difficulty 3: blocking code
Use setTimeout and setInterval to implement the logic wait function of the program, and in this basic event worker/producer queue model, this is not very elegant in languages without semaphores.

Difficulty 4: multi-thread programming
It is difficult for beginners to quickly adapt to the use of WebWorkers on the browser and child_process cluster on the server.

Asynchronous programming solution
Event Publishing/subscription mode
The events module provided by nodejs itself is a simple implementation of the publishing/subscription mode. Some modules in nodejs also inherit from it:

Var EventEmitter = require ('events'). EventEmitter;
Var ee = new EventEmitter ();
// Define listener 1
Ee. on ('data', function (args ){
// DoSomething1 ();
});
// Define listener 2
Ee. on ('data', function (args ){
// DoSomething2 ();
});
// Define the listener that only runs once
Ee. once ('data', function (args ){
// DoOnce ();
});
Ee. emit ('data ',{});
Launch an event directly through emit. The corresponding method defined above will be executed in the defined order and the passed parameters will be received. The API is very simple, but some additional things also need to be understood.
1. If more than 10 listeners are added to an event, a warning will be given. However, you can use ee. setMaxListeners (0) to remove this restriction.
2. the EventEmitter object treats the error event specially. If the error event is triggered during running, EventEmitter checks whether a listener has been added to the error event. If yes, this listener is available for processing. If it is not added, it will be thrown as an exception. if this exception is not caught externally, the thread will exit. A robust EventEmitter instance should handle the error event.

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.