【发布时间】: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.js 和 c.js 并将解析的值导入模块之前,模块加载器似乎实际上等待 async wait 函数解析。
我敢打赌,这在几年前是行不通的。
谁能告诉我这个功能叫什么?是 ES 本身的特性,还是 node 的模块加载器系统的特性?
【问题讨论】:
标签: javascript node.js async-await export es6-modules