0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
J. Doe
  • 1,291
  • 2
  • 10
  • 19
  • The `targetImage` you export is a Promise. So assuming you have `let targetImageValue = require('getImage.js')` then it has to be `targetImageValue.then(value => { console.log('Output: ', value); });` – t.niese Aug 16 '19 at 05:41
  • `var targetImage = data.readFile(path).then(...` means that `targetImage` will be a Promise that resolves once that `.then` runs. To use it elsewhere, you need to call `.then` on it as well – CertainPerformance Aug 16 '19 at 05:41
  • @t.niese, how is `targetImage` a promise? In the example at the link posted, is he creating a promise when he uses `httpGet()` below? – J. Doe Aug 16 '19 at 05:43
  • @CertainPerformance, in the example link posted, when the author does `httpGet('http://example.com/file.txt') .then( function (value) { console.log('Contents: ' + value); }, function (reason) { console.error('Something went wrong', reason); })`, is he again creating a promise? – J. Doe Aug 16 '19 at 05:44
  • 1
    Yes, every time you call `.then` on something that's a Promise, you create another Promise. If that `httpGet(..).then` was saved to a variable, you'd have to call `.then` on it to run code when it resolves – CertainPerformance Aug 16 '19 at 05:45
  • 1
    `data.readFile(path)` returns a Promise. On that Promise you call `.then()` the `then` function itself returns another Promise. On that Promise you call `catch()` and that catch also Returns a Promise, and that final Promise is then saved in `targetImage`. – t.niese Aug 16 '19 at 05:45
  • @CertainPerformance, it helps. Thank you. :) – J. Doe Aug 16 '19 at 05:47
  • @t.niese, it is helpful. Thank you! :) – J. Doe Aug 16 '19 at 05:47
  • Additional notes: **1.** Doing a `fs.existsSync(path)` before a `fs.readFileSync` does not protect you from the case that `fs.readFileSync` does not find any file. Another process could delete the file between the `fs.existsSync(path)` check and the `fs.readFileSync` call. So you need to handle the _"file does not exist"_ error case for the `fs.readFileSync` directly. And if you do that you can get rid of the `fs.existsSync(path)`. **2.** wrapping a completely synchronous code into a `new Promise(function(resolve, reject){ })` does not make to much sense. – t.niese Aug 16 '19 at 05:52
  • @t.niese, yes, what you say makes sense to me. Both the things I am doing are absurd. I will rectify them shortly. Thanks again! – J. Doe Aug 16 '19 at 05:55

0 Answers0