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!