I am experimenting with the best way to standardise my dynamic import()
expressions when importing javascript modules.
import()
returns a promise, so, to handle the asynchronous steps after theimport()
expression, I can use either:
.then()
syntax; orasync
/await
syntax
Whilst I am quite familiar with the older XHR2
approach and somewhat familiar with ES2015 .then()
syntax, I am less familiar with async
/ await
syntax.
I understand that I can only use await
inside a function which has been declared or assigned with async
.
But I am trying to understand why Approach 1 works.
Approach 1:
(async () => {
let myImportedModule = await import('/path/to/my-module.js');
myImportedModule.myFunction1();
myImportedModule.myFunction2();
})();
But Approach 2 does not.
Approach 2:
(async () => {
await import('/path/to/my-module.js');
myFunction1();
myFunction2();
})();
Additional Notes:
Clearly I have something wrong, but I thought Approach 2 would be the async
/ await
equivalent of this snippet (using .then()
syntax):
import('/path/to/my-module.js')
.then((myImportedModule) => {
myImportedModule.myFunction1();
myImportedModule.myFunction2();
});
but that it would enable me to access myFunction1
and myFunction2
directly, without needing to give a name to the resolved Promise
.
then
version. Otherwise the meaning would be completely different. To understand this, think about how names are resolved and how they can be shadowed. \$\endgroup\$const {f, g} = await import(...);
)? If you want them at module scope, that's highly problematic. \$\endgroup\$import()
. \$\endgroup\$export default expression
, a habit I got into because of loader-interop issues and then became enamored of. I fully understand why many prefer to export multiple bindings though. \$\endgroup\$