【问题标题】:export awaited value as ESM module将等待值导出为 ESM 模块
【发布时间】:2021-10-12 21:47:09
【问题描述】:

我刚刚注意到,以下在节点 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 并将解析的值导入模块之前,模块加载器似乎实际上等待 async wait 函数解析。

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

谁能告诉我这个功能叫什么?是 ES 本身的特性,还是 node 的模块加载器系统的特性?

【问题讨论】:

    标签: javascript node.js async-await export es6-modules


    【解决方案1】:

    它被称为顶级await。这个here有明确的解释,在第二个选项里。

    【讨论】:

    猜你喜欢
    • 2021-01-16
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2023-01-31
    相关资源
    最近更新 更多