Chapter III from blocking sequential programming styles to event-driven and asynchronous programming styles

Source: Internet
Author: User
Tags readfile

an asynchronous and blocking, event-driven and sequential execution


1. What is asynchronous, what is event driven, what is the benefit of asynchrony, what is the disadvantage a June and B June are planning to go to the bank today to do something, and then go to the supermarket to buy some daily necessities. They all came to the bank, a to the automatic teller machine there began to line up, there are probably 20来 people, she can only wait in line, and then she went to the supermarket after the money. B went to the queue to smoke a number, he looked at the front there are many people, expected to compare long events, and then go to the supermarket next door to find things to buy, hear the bank broadcast its own number, then come back to the bank affairs.

for A-June, we call synchronization, the program can only be executed in a predetermined order, when the time-consuming operation, you need to wait for it to complete to perform the next task. For a June, he has a good thing is step, not afraid of unexpected situations, such as not enough money on the body of these problems. But it will take more time.

for B-June, we call async, the program encountered the need to wait for a long operation, do not wait for it to complete the next task immediately, and then wait until the long operation is completed and then go back to continue to deal with the subsequent issues. This is a good time to save, but if you have more things, it becomes a bit messy, bad management.

and the bank's broadcast will trigger the B-June back to the bank, which we call event-driven. Of course this is a lot of bad places, such as error handling will be more troublesome, things will become messy and difficult to organize.

2 How to read node's code

because of the event-driven existence, we can not look like some other code in order to view, we should first preview the code, and then the "event" as the keyword, search for code, find the beginning of the code entry.

For example, a simple Web program:

var http = require (' http ');

var url = require (' URL ');

var Web = function (req,res) {

this.req = req;
this.res = res;

};

web.prototype['/hello ' = function () {
this.res.end ("Hello World");
}

Web. prototype['/404 ' = function () {
this.res.
this.res.end ("404 Not Found");
}

Http.createserver (function (req, res) {

 var reqinfo = Url.parse (req.url);
 var web = new Web (req, res);
 var Path = Reqinfo.pathname.toLowerCase ();
 if (path && Web[path]) {
    try{
          web[path] ();
    }catch (Err) {

throw err;
   }

}else{
web[' /404 '];

 }

}). Listen (+);


you can find that if you look at it from the start, it's not going to fit The order of things come on, we should be from http.createserver start here. And the code is at the end of the program.
so looking at node's code, the first thing you need to do is not to look at each code carefully, but to quickly browse and find the right entry.

(PS: In the beginning, I as a PHP programmer into my former company, but unprepared for the 0 Foundation took over a separation of the research to write node semi-finished (semi-finished products are not, because the program can not run) project, I used the PHP habit to look at the code, looking for code ideas, It caused me to be completely puzzled for a week. This pain has been unforgettable, but also thanks to this unforgettable, let me learn all the other languages more handy)

two back adjustment and avoid deep nesting


1. Typical examples of deep nesting

The following function reads the contents of the file as follows:

fs.readfile ('/etc/passwd ', function (err, data) {
if (err) throw err;
console.log (data);
});

So, what do we do when we read two files and merge the contents of these two files together? Most people who touch JS soon may do this:

fs.readfile ('/etc/passwd ', function (err, data) {
if (err) throw err;
fs.readfile ('/etc/passwd2 ', function (err, data2) {
if (err) throw err;
//Handle data and data2 here
  });
});

So what if we're dealing with a number of similar scenarios, not a layer of nesting of callback functions?

We often call this problem "callback black hole" or "Callback Pyramid":

DOASYNC1 (function () {DOASYNC2 () {doAsync3 (function () {DOASYNC4 (function ()} () {      //.... doasync N (..)})})  

1. Poor code readability (very serious)
2. Debugging difficulties
3. Difficult to troubleshoot after an exception occurs
4. Rewriting difficulties.

A callback black hole is a subjective term, like nesting too much code, and sometimes it doesn't matter. To control the order of calls, the asynchronous code becomes very complex, which is the black hole. One question is very appropriate to measure how deep a black hole is: How much refactoring pain Would you endure if DOASYNC2 before doAsync1? The goal is not simply to reduce the number of nested layers, but to write modular (testable) code that is easy to understand and modify.



2.node v0.1.1 version after the workaround


2.1Generator

      generator is a lightweight process the introduction of generator itself is not intended to solve asynchronous problems, but the yield and next interfaces happen to can solve the problem of the deep callback, let us accept the result of the asynchronous, continue to complete the next task, and the purpose of the callback is consistent.
     Generatoris actually aiterators. It's like a function that can return an array, has arguments, can be called, and generates a series of values. However, instead of generator the values in the array and then returning them one at a time, it takes less resources, and the caller can start processing several values at the beginning. In short, generator looks likefunction, but behaves likeiterators. The sense that the code uses function* to denote generator is very similar.

2.2generator use, yied,next,function* and co libraries.

(if you're familiar with the go language or Python, you're definitely not a stranger to this.)
node's support for generator is from v0.11.2started, but because it hasn't been released yet, you need to specify the--harmony or--harmony-generator parameter to enable it (Nodejs uses the V8 engine, and the V8 engine has partial support for things in ES6, so you can use Nodejs in ES6.) But since a lot of things are just drafts, maybe the official version will be deleted, so it hasn't been introduced directly. Instead, put them in harmony (harmony) mode, if you need to, you need to specify .
For example, to run a file test.js we need

#node--harmony test.js

#forever start-c "Node--harmony" test.js//if using forever boot, this is also forever support ES6 method


first define a simple generator and use it:

function*Foo(x) {  YieldX +1;var y =yieldNull Console.log (y);returnx + y;} var foo =Foo(5); foo.Next();//{Value: 6,Done : false}foo.Next();//{Value:NullDone : false}foo.Next(8);//{Value:  -,Done : true}

generator is similar to the normal function, except that there is a  * number behind the  function  keyword. When generator is called, a generator object is returned, which holds the internal execution state of generator. Each time you call the next method of generator, you get an object that contains the result of the execution, containing two fields  value  and  done .  value  is the flag that this execution generator's return value, done  to whether generator has finished executing. If you call the next method on a  done  Generator object that is  true , the Error:generator has already finished  error is thrown.

A new keyword yield is used in generator, which functions as much as return, in addition to the ability to return values from generator to external use, and to pause the execution of the generator. You can also pass the value to generator's last interrupt position via next (so y gets 8) and continue executing the code from the last interrupt location.

we focus on Next's code

var foo = foo (5); Create object, code does not execute foo.Next();//{Value: 6,Done : falseNext comes in undefined and executes the result foo x+1 returns X+1.Next();//{Value:NullDone : falseNext passes in the undefined, executes null, and returns the result of the null foo.Next(8);//{Value:  -,Done : true} passed in 8 and was received by Y Console.log (y) and return x+ y;



Cond

three loops and recursive loops


Four error handling


Five conventions of the programming style


Chapter III from blocking sequential programming styles to event-driven and asynchronous programming styles

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.