In-depth understanding of node. JS Event-driven callbacks

Source: Internet
Author: User
Tags node server

relationship of callbacks and asynchronous invocations

First, make it clear that callbacks are not asynchronous calls, and callbacks are a way of handling the results of asynchronous function execution. In an asynchronous invocation, if we want to return the result of execution and process it, it can be resolved by means of a callback. To be able to better differentiate between callbacks and asynchronous callbacks, let's look at a simple example with the following code:

function waitfive (name, Function_ Name) {var pus = 0; var currentdate = new Date (); Span class= "Hljs-keyword" >while (Pus < 5000) {var now = new date (); pus = now-currentdate;} function_name (name);} function echo ( name) {console.log (name);} Waitfive ( "Bob", Echo);           

The above code is a callback logic, but not an asynchronous code logic, because it does not involve the asynchronous invocation interface of node. js. When the waitfive () function executes, the entire code execution waits for the execution of the waitfive () function, not the waitfive that is not ended as an asynchronous call, and continues to execute Console.log (' its-over ');

Therefore, the callback is also a blocking call.

Asynchronous functions often do not return execution results directly, but instead return the execution result to the callback function in an event-driven manner, and then process the corresponding logical code in the callback function.

Many API invocation patterns in node. JS are called asynchronously, so it is important to understand asynchronous calls, synchronous calls, and callbacks during the learning of node. js.

Why do asynchronous functions require a callback function?

Let's look at one such example:

var dns = require(‘dns‘); // require dns 模块var address = dns.resolved4(‘www.baidu.com‘, function(address){});//dns 同步解析console.log(address);

When we get the address value, an exception appears, indicating that the address does not have a undefined defined. Print out address, you can see the second example result is null, the reason is very simple, the asynchronous function Dns.resolve4 () is not executed at the end of the execution to Console.log (address), so the final address is null. Now that the Async function has this problem, we can use callbacks to get the function. The following code, through the callback function, gets the result of the execution address value:

var dns = require(‘dns‘);dns.resolve4(‘www.baidu.com‘, function(address){ console.log(address);})
node.js--Event-driven callbacks

Why is it meaningful for us to write Web applications with node. js?

When we use the Http.createserver method, of course we don't just want a server that listens on a port, we also want it to do something when the server receives an HTTP request. The problem is that this is asynchronous: The request can arrive at any time, but our server is running in a single process.

When writing PHP applications, we are not worried at all: whenever a request comes in, the Web server (usually Apache) creates a new process for the request and starts executing the appropriate PHP script from start to finish.

Let's start by looking at a simple, simple HTTP server based on node. JS:

var http = require("http");http.createServer(function(request, response){ response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end();}).listen(8888);

So in our node. JS program, when a new request arrives at Port 8888, how do we control the process?

Well, that's where Node.js/javascript's event-driven design can really help-although we have to learn some new concepts to master it. Let's take a look at how these concepts are applied in our server code.

We created the server and passed a function to the method that created it. Whenever our server receives a request, the function is called. We don't know when this is going to happen, but we now have a place to deal with the request: It's the function we passed in the past. It does not matter whether it is a pre-defined function or an anonymous function. This is the legendary callback (asynchronous callback in node. js).

Let's try to figure out the concept of [asynchronous Callbacks in node. js].

How do we prove that after the server is created, there is no HTTP request coming in immediately, our callback function is not called, our code will continue to work? Try this:

var http = require("http");http.createServer(function(request, response){ console.log("Request received."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end();}).listen(8888);console.log("Server has started.");

Note: In the place where the anonymous callback function was triggered, we output a text with Console.log, and after the HTTP server has started working, it also outputs a text.

When we run node server.js as usual, it will output "server has started." On the command line immediately. When we make a request to the server (in the browser to access http://localhost:8888), "request received." This message will appear on the command line. (Note that when we access the Web page on the server, our server may output two times "Request received.") That's because most browsers try to read Http://localhost:8888/favicon.ico when you visit http://localhost:8888-This is the event-driven asynchronous server-side JavaScript and its callbacks!

In-depth understanding of node. JS Event-driven callbacks

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.