What is the await keyword effect when importing ESM modules

Viewed 1474
1 Answers

[Not Duplicate]

  • The await import() imports an EC Module statically (instead of import() imports dynamically), it's very similar to the CommonJS module require() syntax, this is the only purpose of the top level await keyword

Supported by: (node.js 14.8.0) (chrome 89) (Firefox 89) at the time of writing this

  • So why using it if we already have all those beautiful static import syntaxes? (like: import * as imp from './someModule.mjs)
  • Well it's more straightforward to write and easier to remember (ex: await import('./someModule.mjs') statically requires the 'someModule' and returns its exported data as {default:'someDefVal'[, ...]} object
// static import -----------------------------------// blocks this module untill './module1.mjs' is fully loaded 
  // traditional static import in EC modules 
    import * as imp from './module1.mjs'; 
    console.log( imp );                             // -> {default:'data from module-1'}
    
  // static import with await import() (does the same as above but is prettier) 
    console.log( await import('./module1.mjs') );   // -> {default:'data from module-1'}
    
    function importFn1(){                           // the await import() is a satic import so cannot be used in a function body
        // await import('./module1.mjs');           // this would throw a SyntaxError: Unexpected reserved word 
    }
    
    
// dynamic import ----------------------------------// does not block this module, the './module2.mjs' loads once this module is fully loaded (not asynchronous)
    import('./module2.mjs') 
        .then((res)=>{ console.log(res) })          // -> {default:'data from module-2'}
        .catch((err)=>{ console.log(err) });
        
    (function ImporFn2(){
        import('./module2.mjs')                     // dynamic import inside a function body 
            .then((res)=>{ console.log(res) })      // -> {default:'data from module-2'}
            .catch((err)=>{ console.log(err) });
    })();
    
    console.log( '----- MAIN MODULE END -----' );
  • result in console
{ default: 'data from module-1' }
{ default: 'data from module-1' }
----- MAIN MODULE END -----
{ default: 'data from module-2' }
{ default: 'data from module-2' }
Related