Content: Callback functions, blocking/synchronizing, non-blocking, and asynchronous differences, blocking and non-blocking code instances
node. JS callback function
The immediate manifestation of node. JS asynchronous programming is callbacks.
Asynchronous programming relies on callbacks to implement, but it cannot be said that the program is asynchronous after using the callback.
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.
Block/sync: Make a phone call until someone has to answer it.
Non-blocking: Make a phone call no one to answer, every 10 minutes to call again, know someone to answer so far
Async: Make a phone call no one answer, go to voicemail message (register), and then wait for the other party to return (call back)
####################################################################################
Blocking Code Instances
Input.txt:love A
var fs = require ("FS"); var data = Fs.readfilesync (' input.txt '); Console.log (data.tostring ()); Console.log ("program execution ends!");
Execution Result:
Love A
Program execution ends!
####################################################################################
Non-blocking code
var fs = require ("FS"); function foo (err, data) { ifreturn console.error (err); Console.log (Data.tostring ());} Fs.readfile (' input.txt ', foo); Console.log ("program execution ends!");
Execution Result:
Program execution ends!
Love A
The callback function typically appears as the last parameter of the parameter:
function foo1 (name, age, callback) {}
function Foo2 (value, Callback1, Callback2) {}
Like the example above
This is not clear, see the blocking code here, Readfilesync,sync this should be synchronous method, so must be executed, the second example of the ReadFile is an asynchronous method, do not block, directly proceed to the next step.
5. Node. JS callback function