My path to Node. js Learning (iii) -- node. js functions, callbacks, synchronous and asynchronous code, and event loops _ node. js

Source: Internet
Author: User
This article mainly introduces several important knowledge points of node. js: The Role of node. js, callback, synchronous and asynchronous code, event loop 1, and the role of node. js,

The meaning of I/O. Move the mouse to see the move of the mouse on the screen. Terminal input and output. And so on)

The problems that node. js wants to solve (processing input, input, and high concurrency. For example, an online game may contain millions of players, millions of input, and so on. js is applicable to: Node when an application needs to send and receive data over the network. js is the most suitable. This may be a third-party API, a networked device, or real-time communication between a browser and a server)

The meaning of concurrency (the term "concurrency" describes that a thing may occur at the same time and interact with each other. Node's event-based I/O model eliminates the need to worry about mutual lock and concurrency, which are common problems in multi-thread asynchronous I/O)

Demo network I/O

Js Code

Var http = require ('http'), urls = ['www .baidu.com ', 'www .10jqka.com.cn', 'www .duokan.com ']; function fetchPage (url) {var start = new Date (); http. get ({host: url}, function (res) {console. log ("Got response from:" + url); console. log ("Request took:", new Date ()-start, "ms") ;}) ;}for (var I = 0; I
 
  

Name it, node. js
We run node. js in the terminal.
Output:

We asked node. js to access the three URLs and report the response and the time it took.
We can see that the output time is different. Affected by various factors, such as DNS request resolution time, server busy programs, and so on.

Why javascript is an event-driven Language
Javascript revolves around the event architecture initially related to the Document Object Model (DOM. Developers can do things when an event occurs. These events include clicking an element and loading the page. When using events, developers can write event listeners, which are triggered when an event occurs.

Ii. Callback)
1. What is callback?
2. Analyze callback

Callback refers to passing a function as a parameter to another function, which is usually called after the first function is completed.

Example: The hide () method in jquery,
Js Code

1,$("p").hide('slow'); 2,$("p").hide('slow',function(){alert("The paragraph is now hidden")}); 

Callback is optional,
1. Callback is not required.
2. There is a callback. When the section is hidden, it will be called and an alert prompt will be displayed.

To see the difference between code with and without callback
Js Code

$("p").hide('slow'); alert("The paragraph is now hidden");//1  $("p").hide('slow',function(){alert("The paragraph is now hidden")});//2 

1. There is no callback, And the execution sequence is the same. However, we can see that the p section is not completely hidden, and alert will come out.
2. There is a callback, And the execution is completed in alert

Profiling callback
Js Code

function haveBreakfast(food,drink,callback){   console.log('Having barakfast of' + food + ', '+ drink);   if(callback && typeof(callback) === "function"){     callback();   } }  haveBreakfast('foast','coffee',function(){   console.log('Finished breakfast. Time to go to work!'); }); 


Output:

Having barakfast of foast,coffeeFinished breakfast. Time to go to work!

A function is created here. There are three parameters, and the third parameter is callback. This parameter must be a function.
The haveBreakfast function records what it eats to the console and calls the callback function that is passed to it as a parameter.

How to Use callback in Node. js

Example of using the filesystem module in node. js to read file content from disk

Js Code

var fs = require('fs');  fs.readFile('somefile.txt','utf8',function(err,data){   if(err) throw err;   console.log(data); });

The result is: Content in somefile.txt.
1. The fs (filesystem) module is requested for use in scripts
2. The file path on the file system is provided to fs. readFile as the first parameter.
3. The second parameter is utf8, indicating the file encoding.
4. Provide the callback function as the third parameter to the fs. readFile method.
5. The first parameter of the callback function is err, which is used to save the error returned when the file is read.
6. The second parameter of the callback function is hit. The user saves the data returned from the Read File.
7. Once the file is read, the callback will be called.
8. If err is true, an error is thrown.
9. If err is false, the data from the file can be used.
10. In this example, the data is recorded on the console.

The http module allows developers to create http clients and servers.

Js Code

var http = require('http');  http.get({host:'shapeshed.com'},function(res){   console.log("Got response:" + res.statusCode); }).on('error',function(e){   console.log("Got error:" + e.message);  }); 

Result: Got response: 200
1. Request the http module for use in the script
2. Two parameters are provided for the http. get () method.
3. The first parameter is the option object. In this example, you must obtain the homepage of shapeshed.com.
4. The second parameter is a callback function with the response as the parameter.
5. When the remote server returns a response, the callback function is triggered.
6. Record the response status code in the callback function. If there is an error, record it.

Next, let's see that four different I/O operations are happening, and they all use callback.

Js Code

var fs = require('fs'),   http = require('http');  http.get({host:'www.baidu.com'},function(res){   console.log("baidu.com"); }).on('error',function(e){   console.log("Got error:" + e.message);  });  fs.readFile('somefile.txt','utf8',function(err,data){   if(err) throw err;   console.log("somefile"); });  http.get({host:'www.duokan.com'},function(res){   console.log("duokan.com"); }).on('error',function(e){   console.log("Got error:" + e.message);  });  fs.readFile('somefile2.txt','utf8',function(err,data){   if(err) throw err;   console.log("somefile2"); }); 

Can we know which operation returns first?
The guess is that the two files read from the disk are returned first, because the network is not required, but it is hard to say which file is returned first, because we do not know the file size. For obtaining the two homepages, the script needs to enter the network, and the response time depends on many unpredictable tasks. The Node. js process will not exit until a registered callback has been triggered. Callback is the first way to solve unpredictability. It is also an efficient way to process concurrency (or more than one thing at a time.
The following is the result of my execution.



Synchronous and asynchronous code

First read the code and synchronize (or block) the code.

Js Code

function sleep(milliseconds){   var start = new Date().getTime();   while((new Date().getTime() -start) < milliseconds){    } } function fetchPage(){   console.log('fetching page');   sleep(2000);   console.log('data returned from requesting page'); } function fetchApi(){   console.log('fetching api');   sleep(2000);   console.log('data returned from the api'); } fetchPage(); fetchApi(); 


When the script is running, the fetchPage () function is called until it returns, and the script is blocked. Before the fetchPage () function returns, the program cannot be moved to the fetchApi () function. This is called a blocking operation.
Node. js almost never uses this encoding style, but calls the callback asynchronously.
Check the encoding below ,,

Js Code

var http = require('http');  function fetchPage(){   console.log('fetching page');   http.get({host:'www.baidu.com',path:'/?delay=2000'},     function(res){       console.log('data returned from requesting page');     }).on('error',function(e){       console.log("There was an error" + e);     }); } function fetchApi(){   console.log('fetching api');   http.get({host:'www.baidu.com',path:'/?delay=2000'},     function(res){       console.log('data returned from requesting api');     }).on('error',function(e){       console.log("There was an error" + e);     }); } fetchPage(); fetchApi(); 

When this code is allowed, the fetchPage () function is no longer returned, and the fetchApi () function is immediately called. The code is non-blocking by using callback. Once called, both functions will listen to the remote server's return and trigger the callback function.
Note that the returned sequence of these functions cannot be guaranteed, but is related to the network.

Event Loop

Node. js uses javascript event loops to support its asynchronous programming style. Basically, the event loop allows the system to save the callback function first, and then run the event in the future. This can be the data returned by the database or the HTTP request. Because the execution of the callback function is postponed until the event is reversed, the execution does not need to be stopped. The control flow can be returned to the Node runtime environment, so that other tasks can occur.

Node. js is often regarded as a network programming framework because it is designed to handle the uncertainty of data streams in the network. This design facilitates the use of event loops and Callbacks. Similar programmers can write asynchronous code that responds to network or I/O events.

The rules to be followed are: the function must return quickly, and the function must not be blocked. Operations that run for a long time must be moved to another process.
Node. js is not suitable for processing large amounts of data or running computing for a long time. Node. js is designed to push data on the network and complete it instantly.

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.