A detailed explanation of the loop invocation problem for modules in node. js

Source: Internet
Author: User

First, let's take a look at the code, each of which actually represents a JS file. So the following is actually a three JS file. The first one is the main file that we want to run, and the next two are A, b files.

From above you can read a, b two modules referencing each other, the above output results are as follows:

So how does that make sense?

First look at the main module, first output main starting; The A module is then called;

Then we enter the A module, first output a starting; Then the B module is called;

Then we go into the B module, first output B starting; Then call a module;

But the problem is, a module has not been initialized well, so a module will return a unfinished copy, you can understand to return an empty object {};

However, a module in the reference to the B module, the front of a exports.done = flase;

This is not the same, at this time is not an empty object, but {done:flase}; But if it is an empty object, it will output undefined;

So output in B, A.done = Flase , then run the B module until the last output b.done ;

Then a module starts to run down, output in A, B.done = True, because the last B module output is done=true AH;

Then output A.done ; A module is finished running.

To this, a, b two modules are loaded, in main although there is a reference to the B module, but will not be executed.

And then the last thing we see is the output in Main, A.done=true, B.done=true.

variants

We change the statement of a, B module as follows:

We removed two of the lines of the black line, and now what does the output turn out to be?

Please see:

Here is not carefully analyzed, left to you to analyze.

A detailed explanation of the loop invocation problem for modules in node. js

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.