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