Home > Net >  export awaited value as ESM module
export awaited value as ESM module

Time:10-12

I just noticed, that the following is working in node 14.17.3:

a.js:

console.log("a.js executes")
async function wait(){
    console.log('wait runs')
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{resolve("foo")},3000)
    })
}
export default await wait()

b.js:

import data from './a.js'
console.log("b.js executes")

export default function test(){
    console.log("b.js: imported from a.js:",data)
}

c.js:

import data from './a.js'
console.log("c.js executes")

export default function test(){
    console.log("c.js: imported from a.js:",data)
}

d.js:

import test_b from './b.js'
import test_c from './c.js'

test_b()
test_c()

When i run d.js i get the following output, while there is a 3 second delay between the second and the third line:

a.js executes
wait runs
b.js executes
c.js executes
b.js: imported from a.js foo
c.js: imported from a.js: foo

This is exactly what i want, but i don't understand why this works. The module loader seems to actually wait for the async wait function to resolve, before executing b.js and c.js and importing the resolved value into the modules.

I would bet, that this did not work a couple of years ago.

Could someone tell me what this feature is called? Is it a feature of ES itself, or of the module loader system of node?

CodePudding user response:

It's called top-level await. There is a clear explanation of this here, in the second option.

  • Related