node.js - javascript - Why is there a spec for sync and async modules? -
i have finished reading article on javascript modules. can understand commonjs modules synchronously loaded while amd modules asynchronously loaded.
what don't understand how can module become magically synchronous if write in commonjs format, or how becomes magically async if write in amd format. mean javascript not have define
or require
keyword even. are specs not libraries.
i mean behaviour of module loading dependent on module loader , not how module structured. , if case why follow coding pattern different types of modules ?
am right in assuming libraries in nodejs world synchronously loaded, regardless in format written. , modules in browser space asynchronously loaded.
if above assumption correct why there spec umd ? mean if script loads based on environment present in why make spec universal module loading ?
can me confusion ?
this question. it's subject caused lot of heated discussion in node community. have understanding of it's should read:
- node.js, tc-39, , modules james m snell ibm
- es6 module interoperability - node.js enhancement proposals
- in defense of .js - proposal node.js modules dave herman, yehuda katz , caridy patiƱo
- discussion on pull request #3 of node-eps (002: es6 module interop)
now, answering question - why there spec sync , async modules? because usecases prefer synchronous loading of modules, server-side modules in node.js want load need before start serving requests, , usecases prefer asynchronous loading of modules, in browser when don't want block rendering thread while load dependencies.
there no option synchronous loading in browser because make browser not responsive.
you argue might use asynchronous loading on server you'd either have return promises instead of modules require()
or take callbacks. either way make complex code uses lot of modules more complicated.
another issue caching , mutation of loaded modules. synchronous module loading using require
load module once , other calls require
same module in entire code base (for process) return cached response, same object every time. part of code can modify object , available other part of code. usecases use feature more complex implement. additionally order of loading , executing code harder predict.
to sum answer question, there arguments both ways of loading modules , neither of ways clear winner every scenario. both needed , both have specs standardize behavior.
read articles linked more detailed understanding.
Comments
Post a Comment