0

How do you return the data returned from an event back to the outside function?

const https = require('https');

function get_message(){
    https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
        let data = '';
        resp.on('data', (chunk) => {
            data += chunk;
        });
        resp.on('end', () => {
            console.log("message appears here: ", JSON.parse(data).explanation);
            return JSON.parse(data).explanation; // doesn't return?
        });
    });
}

console.log("but not here: ", get_message())

I can make it work using a Promise but it complicates the code. Is there something simpler?

function get_message(){
    return new Promise((resolve,reject)=> {
        https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
            let data = '';
            resp.on('data', (chunk) => {
                data += chunk;
            });
            resp.on('end', () => {
                resolve( JSON.parse(data).explanation )
            });
        });
    });
}

get_message().then((msg)=>{
    console.log("this works: ", msg)
})
Jon Wilson
  • 726
  • 1
  • 8
  • 23
  • Nope, that's pretty much it. – deceze Nov 13 '20 at 16:19
  • The only thing simpler than promises is async/await (and that's not an alternative to promises, that is just a nicer syntax to consume promises). Is there a reason you're not using async/await syntax? – TKoL Nov 13 '20 at 16:31
  • It complicates the calling code. I want to resolve it within the function. – Jon Wilson Nov 13 '20 at 16:36
  • But to answer your question directly TKoL, I don't see where you would put an await in this case. How would that work? – Jon Wilson Nov 13 '20 at 16:46

0 Answers0