我剛剛注意到,以下內容在節點 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)
}
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
這正是我想要的,但我不明白為什么會這樣。模塊加載器似乎實際上等待異步wait函式決議,然后執行b.js并將c.js決議的值匯入模塊。
我敢打賭,這在幾年前是行不通的。
Could someone tell me what this feature is called? Is it a feature of ES itself, or of the module loader system of node?
uj5u.com熱心網友回復:
It's called top-level await. There is a clear explanation of this here, in the second option.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/310137.html
標籤:javascript node.js async-await export esm
上一篇:被漢堡選單困住了
