In file readFile.js
, function readFile()
is defined as below:
function readFile(path) {
return new Promise(function(resolve, reject){
if(!fs.existsSync(path)) {
console.log('Will throw error now!');
reject("memes.json file does not exist");
}
else {
//File exists
console.log('File found');
var data = fs.readFileSync(path, 'utf8');
resolve(data);
}
})
}
module.exports.readFile = readFile;
In file getImage.js
, targetImage
is defined as below:
var targetImage = data.readFile(path)
.then(function(value) {
var jsonData = JSON.parse(value);
for(let i=0; i<jsonData.length; i++) {
if(jsonData[i].title == memeImage) {
console.log('Visit URL: ', jsonData[i].image);
return jsonData[i].image;
}
}
})
.catch(function(err) {
console.log('Encountered some error during reading file');
return 'Errored out :(';
});
module.exports = targetImage;
Finally, file modifyImage.js
simply has:
console.log('Output: ', targetImageValue);
When I run the above program as node ./lib/modifyImage.js -n Determined
, I get the following output:
File found
Output: Promise { }
Visit URL: http://example.com/pqr.png
My question is - why do I get: Output: Promise { <pending> }
? I am following the example here, so I expect the promise is getting fulfilled in readFile()
when I call reject()
and resolve()
. I think I am consuming the promise using .then()
in getImage.js
. Why does the program say promise is still pending? What am I missing?