I have a very simple function here trying to grab a post from r/askreddit.
const simple_get = require('simple-get');
function get_post() {
simple_get('https://reddit.com/r/askreddit/random.json', (err, res) => {
if (err) {
console.log(err);
}
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
var post = JSON.parse(JSON.stringify(eval('(' + body + ')')))
console.log(post);
return post;
});
});
}
console.log(get_post());
The function returns undefined. However, when post
is outputted on line 17 (inside the function), it returns the correct object. Here are some logs:
undefined.....reddit.js:23
Array(2) [Object, Object].....reddit.js:17
Alongside simply returning post
, I have tried making a global variable and setting that to post
. That also didn't work. I need it as a function so I can set it in a while loop to do things like get a new post if it's a mod post, so alternatives to that would also be appreciated.
Node version 10.15.0 with simple-get 3.1.0 on MacOS Mojave 10.14.6.
Thanks for the help :)