-1

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

Community
  • 1
  • 1
helpme
  • 11
  • 4
  • 1
    Three issues because `simple_get()` is asynchronous and non-blocking. 1) It's timing. `res.on('end', ...)` happens long AFTER your function returns. 2) You don't actually have any return value from `get_post()`. Your `return` is inside a callback, not from `get_post()`. 3) The value you want to return is NOT available yet when `get_post()` returns. So, see the question yours has been marked a duplicate of for solutions. You will need to either return a promise which you resolve with the proper value or you will need to accept a callback that you can call with the final value. – jfriend00 Dec 04 '19 at 00:38

1 Answers1

0

simple_get is an async function, it means your code goes through console.log() before it actually receives any response

meisam
  • 465
  • 6
  • 18