0

This might ostensibly look like a duplicate of this one, but it is not.

In the code segment below, I am trying to output myData from outside the getData() function:

var myData, obj;

function getData() {
    return new Promise(function (resolve, reject) {
        fs.readFile('./json/data.json', 'utf8', function (err, data) {
            if (err) {
                console.log("Error in reading data.json file");
                return Promise.reject(err);
            }

            try{
                obj = JSON.parse(data);
            }
            catch(error) {
                console.log('Error in parsing the data.json file');
                return Promise.reject(error);
            }
            obj.forEach(element => {
                const options = {
                    resolveWithFullResponse: true
                }
                if (element.title == Image) {

                    rp.get(element.image, options)
                    .then( function (response) {

                        if(response.statusCode == 200) {
                            myData = Buffer.from(response.body).toString('base64');
                            myData.replace("myData:image/png;base64,", "");
                            console.log(myData);
                            console.log('+++++++++++++++++++++++++++++++++');

                            return Promise.resolve(myData);
                        }
                    })
                    .catch( function(error) {
                        console.log('Error in downloading the image via request()');
                        return Promise.reject(error);
                    })
                }
            })
        });
    })
}

getData()
    .then(function (myData) {
        console.log(myData);
        console.log('-----------------------------------------------------');
    })
    .catch(function (err) {
        console.log(err);
        console.log('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
    });

I am able to get the myData (above the ++++++ declaration) printed; but not from within the then() of getData() below. Why so? How can I get myData returned via return Promise.resolve(myData); printed via the then() of getData()? I believe this is a case of passing all the way up, a promise within a promise.

Thanks for your help!

J. Doe
  • 1,291
  • 2
  • 10
  • 19
  • You forgot to call the `resolve` of the Promise constructor – CertainPerformance Aug 08 '19 at 04:05
  • @CertainPerformance, well, where do I call that? – J. Doe Aug 08 '19 at 04:06
  • Instead of `return Promise.resolve(myData);`, call `resolve(myData)`, the return value is ignored – CertainPerformance Aug 08 '19 at 04:06
  • Oh, great, that did the trick! Could you please elaborate? Why is the return value ignored? – J. Doe Aug 08 '19 at 04:08
  • Because the `rp.get` Promise chain is not chained with anything outside – CertainPerformance Aug 08 '19 at 04:09
  • So if I understand correctly, are you saying that there is just a single promise being used? I am a bit confused because I believed I have a promise within a promise. Which is why, I thought I had to return the inner promise and that would bubble up to the outer one. – J. Doe Aug 08 '19 at 04:11
  • Every time you call `.then` or `catch`, you create another Promise. The `rp.get` Promise chain is currently an orphaned expression; it's not being returned, or used anywhere. But even if you returned it, it wouldn't help, because `forEach` ignores the return value of its callback – CertainPerformance Aug 08 '19 at 04:18
  • Looks like I will have to read Promises some more. Thanks for your help! – J. Doe Aug 08 '19 at 04:22
  • 1
    @J.Doe It would really help you understand Promises if you realize that it's just a design pattern, not a language feature or special syntax. You can implement promises yourself in pure javascript (indeed there exists several standards-compliant promise libraries like bluebird written before Promise was standardised). So Promise is just a design pattern like MVC or decorator or factory. It's not something special – slebetman Aug 08 '19 at 04:59
  • @slebetman, thanks for the helpful advise. – J. Doe Aug 08 '19 at 05:33

0 Answers0