Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

216
Visualizações
export awaited value as ESM module

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda