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

195
Visualizações
How can variable be used in promise chaining before declaration?

I came across the following code while working with promises. And it works correctly.

I have read shallowly on how async/await code is run on node. But, in the following code, how is the session variable accessible inside the .then() function? Is it just by sheer chance that this code works or is there something about how node runs async/await code that makes the session variable available inside the .then() function?

async function asyncFunction(
  cb: (filePath: string, session: Session) => Promise<any>,
) {
    readFile().then(filePath => cb(filePath, session));
    const session = await verifyToken();
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Is it just by sheer chance that this code works?

Yes. If verifyToken takes longer than readFile, session will not be initialised when the .then() callback runs and you'll get an exception.

The proper solution for this problem is Promise.all, and not using a callback:

async function asyncFunction(): Promise<[filePath: string, session: Session]> {
    return Promise.all([readFile(), verifyToken()]);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

This is a perfect example of variable scope. In your case this is a sheer chance that this code works. Since the readFile takes longer than verifyToken. As a result, the session variable is initiated before getting callback in then function.

In case the verifyToken takes longer that readFile (even just by a milli-second), then it would throw Cannot access variable before initialization Error.

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