Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!