将等待值导出为 ESM 模块

export awaited value as ESM module

我刚刚注意到,以下内容在节点 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()

当我 运行 d.js 我得到以下输出,而第二行和第三行之间有 3 秒的延迟:

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

这正是我想要的,但我不明白为什么会这样。 在执行 b.jsc.js 并将解析的值导入模块之前,模块加载器似乎实际上是在等待异步 wait 函数解析。

我敢打赌,这在几年前是行不通的。

谁能告诉我这个功能叫什么?是ES本身的特性,还是node的module loader系统的特性?

堪称顶级await。这个在第二个选项里有明确的解释