Nodejs Asynchronous Execution process

Source: Internet
Author: User

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

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.