Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
Why is this function returning undefined when I know that it is not?
function redditCall(subreddit) {
    https.get(`https://www.reddit.com/r/${subreddit}/top.json`, (resp) => {
        let data = " ";
        resp.on("data", (chunk) => {
            data += chunk;
        });
        resp.on("end", () => {
            let json = JSON.parse(data);
            
            if (json.message === "Not Found" || json.message) {
                console.log("That subreddit was not found!");
            } else {
                if (!json.data.children[0].data.secure_media || json.data.children[0].data.secure_media === null) {
                    let postAttachment = json.data.children[0].data.url_overridden_by_dest;
                    // console.log(`That post has an picture attachment: ${postAttachment}`);
                    console.log(postAttachment); // returns the correct link
                    return postAttachment; // Picture Post
                } else {
                    let postAttachment = json.data.children[0].data.secure_media.reddit_video.scrubber_media_url;
                    //console.log(`That post has a video attachment: ${postAttachment}`);
                    return postAttachment; // Video Post
                }
            }
        });
    });
}

As the title says for some reason this function is returning undefined when I have logged postAttachment to the console and it shows the correct string but for some reason when I return postAttachment is says undefined. I've tried doing .toString() and it just shows undefined when I return it when I know for a fact that it is not.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!