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

184
Visualizações
Why is my Async Await not working in NodeJS?

Trying to perform a basic async/await in NodeJS but it is still going out of order.

Code I am trying to run:

var fs = require('fs');
var stringData;

async function find(context) {
  try {
    let text = await readFile('./sql/test.sql', context);
  } catch (e) {
    console.log('Try/Catch Error: ' + e)
  }

  console.log('display')
  console.log('display ' + JSON.stringify(text))
  return
}

async function readFile(file, context) {
  new Promise((resolve) => {
    fs.readFile(file, (error, data) => {
        if (error) {
          throw error;
        }
        stringData = data.toString()
      }),
      (err) => {
        console.log('ERROR: ' + JSON.stringify(err));
      }, () => {
        resolve(1);
      }
  })
};

module.exports.find = find;

When I run the above I get an undefined results for the console.log for text.

I am expecting text to use the await to populate before moving down to the console logs.

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

0

Looks like you are not resolving the promise with the result you get from data.toString(); you need to add resolve(stringData)

PS. In the error handler you are using resolve, you should probably be using reject there

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