Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

96
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda