nurulnabi nurulnabi -4 years ago 108
Node.js Question

examine the following promise code

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);
})

Answer Source

Promise.all is designed to fail-fast - i.e when even one of the promises rejects, all of them are rejected. If you still need the response (resolution or error), you could use something like this —

function readAll(pages) {
    return Promise.all(pages.map(readJson).map(p => p.catch(e => new Error(e))))
        .then(results => results);
}

This returns an array of successful resolutions or Error objects, as catch is never returned. You can then figure out if some exception occurred using some logic like this —

readAll(pages).then(function (allPages) {
    allPages.forEach(function (page) {
        if (page instanceof Error) {
            console.log("-----------------------------------------------");
            console.log(page);
        } else {
            console.log("++++++++++++++++++++++++++++++++++++++++++");
            console.log(page);
        }
    });
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download