I search and read about Asynchronous functions and callbacks. But i was not able to solve my problem for a week. I want to do 'fs readfile' inside loop with order. I try the following but i am not successful.
// on the code below, console.log print the value in random order and 'storedata' is empity.
// my goal is to do readfile in loop orderly and store the value
router.get("/files/readfiles", function(req,res){
var storedata= [];
var filenames= ["file1","file2","file3","file4"];
for (var i=0; i< filenames.length; i++){
fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
if (err) throw err;
storedata.push(data);
console.log(data);
});
console.log(storedata); // this returns empty array
});
I also try in another way:
router.get("/files/readfiles", function(req,res){
var filenames= ["file1","file2","file3","file4"];
filenames.forEach(readfiles);
function readfiles(value) {
var dataread = fs.readFile('views/allfiles/'+ value +'.ejs','utf8')
console.log (dataread);
}
});
on the above try i get an error of: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function.
I am new to Asynchronous methods any help please.