This is a good question. It's a subject that caused a lot of heated discussion in the Node community. To have a good understanding of what it's all about you should read:
Now, answering your question - Why is there a spec for sync and async modules? Because some usecases prefer the synchronous loading of modules, like the server-side modules in Node.js where you want to load everything you need before you start serving requests, and some usecases prefer asynchronous loading of modules, like in the browser when you don't want to block the rendering thread while you load the dependencies.
There is really no option for synchronous loading in the browser because it would make the browser not responsive.
You could argue that you might use asynchronous loading on the server but then you'd either have to return promises instead of modules by require()
or it could take callbacks. Either way it would make any complex code that uses a lot of modules much more complicated.
Another issue is with the caching and mutation of the already loaded modules. With synchronous module loading using require
you only load the
module once and any other calls to require
for the same module in the entire code base (for that process) return a cached response, which is the same object every time. Any part of the code can modify that object and it is available to any other part of the code. Some usecases that use that feature would be much more complex to implement. Additionally the order of loading and executing code would be harder to predict.
To sum up the answer to your question, there are arguments for both ways of loading modules and neither of those ways is a clear winner for every scenario. Both are needed and both have some specs to standardize their behavior.
Read the articles that I linked for more detailed understanding.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…