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

97
Visualizações
Working with custom modules having asynchronous code node js

So, I have a file data.js(the custom module) with the following rough code(to not waste time understanding the whole code):

let data;

async function(){
    data = await something; //the await returns an array, so data has an array
}

module.exports={data} // I am exporting the data array

Now I am requiring the module in app.js

data=require("./data.js");

//Now I am using express to send json data to a url
app.get("/home",(req,res)=>{
    res.json(data);
});

So now if I open the url(localhost:5000/home) I am getting:

{}

Now if I modify data.js to

let data=[]; //I made data an empty array first

async function(){
    data = await something; //the await returns an array, so data has an array
}

module.exports={data} // I am exporting the data array

So now if I open the url(localhost:5000/home) I am getting:

{"data":[]}

Now if I modify data.js again

let data=[]; //I made data an empty array first

async function(){
    data.push(await something); //the await returns an array, and I am pushing into the empty array
}

module.exports={data} // I am exporting the data array

So now if I open the url(localhost:5000/home) finally I am getting:

{"data":[some data]}  //This is how I want

So I want to understand what's the difference between the three data.js files and how exactly does require work with the asynchronous code in the custom module. If I console.log(data) in the app.js file I get empty which is understandable as that is synchronously happening before the asynchronous code of the custom module. But please would someone be able to explain why the first two methods of data.js is not working.

Sorry for the long question!

about 4 years ago · Juan Pablo Isaza
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