I've written a code snippet here that simulates a nested asynchronous process, and below I summarize the order in which the code is executed.
var fs = require ("FS"); Fs.stat (' A.txt ', Callbackone (err,stat) { //execute Callbackone callback function if (err) { Fs.readfile ("Aa.txt", Readfilecallbackone (err,stat) { //execute Readfilecallbackone callback function }) } //Description 1}) Fs.stat (' B.txt ', Callbacktwo (err,stat) { //execute Callbacktwo callback function if (err) { fs.readfile ("Bb.txt", Readfilecallbacktwo (err,stat) { //execute Readfilecallbacktwo callback function }) } //Description 2})
Description 0
The code executes from top to bottom, and because of the asynchronous operation, the code will put two time into the event queue before executing to the two read file function, directly to the location of "description 0":
Events in the event queue at this time:
Callbackone
Callbacktwo
When executing to the "description 0" position, Nodejs will then go to execute callbackone,callbackone inside the file after reading it will also have a callback event, this time into the event queue, event queue event: Callbackone callbacktwo Readfilecallbackone, this will go to the "description 1" position, indicating that Callbackone execution is complete:
Events in the event queue at this time:
Callbacktwo
Readfilecallbackone
At this point, it starts to execute in Callbacktwo, and when the callbacktwo is executed, there is a callback readfilecallbacktwo, which continues to be placed in the event queue.
Events in the event queue: Callbacktwo Readfilecallbackone readfilecallbacktwo, where the code goes to "description 2", indicating that Callbacktwo execution is complete:
Events in the event queue at this time:
Readfilecallbackone
Readfilecallbacktow
It then executes the event in the event queue again, thus completing the entire process.
Nodejs Asynchronous Execution process