node. JS Learning Note (ii)--callback function

Source: Internet
Author: User
Tags readfile

The immediate manifestation of node. JS asynchronous programming is callbacks.

So what is a callback? A callback refers to passing a function as an argument to another function, and is usually called after the first function is complete. It is necessary to indicate that the callback function is not called directly by the implementing party of the function, but is invoked by another party when a particular event or condition occurs, and is used to respond to the event or condition. The callback function is called after the task is completed, and node uses a large number of callback functions, and all node APIs support the callback function. For example, we can read the file while executing other commands, and after the file is read, we return the contents of the file as parameters to the callback function. This will not block or wait for file I/O operations when executing code. This greatly improves the performance of node. JS and can handle a large number of concurrent requests.

  Although asynchronous programming relies on callbacks to implement, it cannot be said that the program is asynchronous after using the callback.

  

Before we begin, we need to understand a few concepts:

What is blocking:

The so-called blocking, that is, each time an operation is performed, the execution of the code will be paused before the next operation can continue until an operation completes.

What is non-blocking:

The so-called non-blocking refers to a callback-based approach that allows the script to perform operations in parallel, and the result of the operation is handled by the callback when the event occurs, thus eliminating the need to wait for the result of an operation to proceed to the next step.

Give me a chestnut to explain the difference between blocking and non-blocking:

You cook at home and find no soy sauce at home, so you stop and go to the store to buy soy sauce. Results The clerk told you that there is no soy sauce, the buyer is outside the procurement, need to wait for a moment to come back. At this time you have two choices: one is to continue in the store waiting for the buyer back, get soy sauce home to continue to cook, second, go home to busy other work, wait a moment to come back to buy soy sauce.

The first choice is actually blocking, and it takes a while before the soy sauce is bought to continue. The second option is a non-blocking approach, first to do other things, and then to buy soy sauce when the time is right. (Of course, this chestnut is a bit dodgy.) I hope you can read my meaning. )

Practice the truth, after the basics of knowledge points, then start knocking code it. The sleeves are dry.

Now over here. The following API is used by the instance:

  

  Read file (Synchronous operation): Fs.readfilesync (file[, Options])

  

  Read file (Asynchronous operation): Fs.readfile (file[, Options], callback)

  Blocking Code Instances

First create a new TXT file, such as Demo2.txt. And then knock something in there, like this:

This is    my second demo!   ******

And then in the same directory to create a new JS script, I named it demo2.js, the code is as follows:

// introduce the FS (filesystem) module in the script using the var fs = require ("FS"); //Sync Read File var data = Fs.readfilesync (' demo2.txt '); // Print Data Console.log (data.tostring ()); Console.log ("------   program execution ends!   ------");

Finally, you can use the node command to run our code! is not very impatient, then come to see it.

// node Command node Demo2.js

CMD Run Effect:

You can see that after reading the file and outputting the contents of the file, the JS script will continue to execute the following console.log ("------Program execution ends!"). ------"). Since it takes time to read and output the file, the script does not go through the other code in the process of reading and outputting, but waits until the contents of the Read and output files are completed before proceeding to the next step. This is called a (synchronous) blocking.

  Non-blocking Code instances

  Demo2.txt is still the same as before. We just need to modify the Demo.js code on the line, the specific code is as follows:

introduce the FS (filesystem) module in the script using the
var fs = require ("FS"); Asynchronously reads a file fs.readfile ( err, data) { ifreturn Console.error (err); // If the read fails, an error is reported Console.log (Data.tostring ()); // output file Content if read success }); Console.log ("program execution ends!");

To see how the results work:

As you can see, because the asynchronous read operation is used, the script continues to execute the following code when the file is read, that is, the script goes down regardless of whether the file is read and output is complete. So you'll see that the Console.log is executed first ("------program execution is finished!   ------") before you see the output" ****** this is my second demo! ". This is called (asynchronous) non-blocking.

  

Above two examples we understand the difference between blocking and non-blocking calls. The first instance finishes executing the program after the file has been read. In the second instance, we don't have to wait for the file to be read, so we can execute the next code while reading the file, which greatly improves the performance of the program.

As a result, blocking is performed sequentially, not blocking is not required in order, so if you need to handle the parameters of the callback function, we need to write it inside the callback function.

  

Do you understand? Anyway I understand (~ ̄▽ ̄) ~

node. JS Learning Note (ii)--callback function

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.