consider the code given below. Here I am reading four files three of which is json and one is html. The function readJson reads file one by one and returns promise either resoved or rejected. So my problem is if first three files are read without any error except the last one index.html
, then the first three files should be logged except the last one. But this not so the program does not print any of the file. why?
var pages = [
"a.json",
"b.json",
"c.json",
"index.html"
];
var fs = require('fs');
function readJson(page){
console.log("this file name is:",page);
return new Promise(function(resolve,reject){
fs.readFile("./"+page,"utf8",function(err,res){
if(err){
reject(err);
}else{
try {
resolve(JSON.parse(res));
} catch (ex) {
reject(ex);
}
}
});
});
}
function readAll(pages){
return Promise.all(pages.map(readJson));
}
readAll(pages).then(function(allPages){
allPages.forEach(function(page){
console.log("++++++++++++++++++++++++++++++++++++++++++");
console.log(page);
});
})
.catch(function(err){
console.log("-----------------------------------------------");
console.log(err);
})