Nodejs callback function

Source: Internet
Author: User

Block Code instance:
Main.js
var fs=require ("fs"); var data=fs.readfilesync ("1.txt"); Console.log (data.tostring ()); Console.log (" end of program execution ");
Non-blocking code instances:

Main.js

var fs=require ("fs"); Fs.readfile ("1.txt")  , Function (err,data) {   ifreturn  console.error (err);   Console.log (Data.tostring ());}); Console.log (" end of program execution ");

1.txt

Hello World

Execute Command: Node main.js

Blocking code results:

Hello World program Execution end

Non-blocking code results:

Program execution End Hello Word

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. The second instance we do not need to wait for the file to be read, so that you can read the file while executing the next code, greatly improving 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.

Nodejs 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.