T
T
TheBeJIIHiu2021-12-10 11:28:46
Node.js
TheBeJIIHiu, 2021-12-10 11:28:46

Why does it return Undefined?

const fetch = require("node-fetch");
let meme;
//import fetch from 'node-fetch';
const fs = require("fs");
function gen() {
fetch(   "https://www.reddit.com/r/memes/hot/.json?count=100"
  )
    .then(res => res.json())
    .then(json => {
      let postID =
        json.data.children[
          Math.floor(Math.random() * json.data.children.length)
        ];
      this.result = {
        image: postID.data.url,
        category: postID.data.link_flair_text,
        caption: postID.data.title,
        permalink: postID.data.permalink
      };
    });
  return this.result;
};

console.log(gen())


Why does it return Undefined?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2021-12-10
@Azperin

Asynchrony. I think this example will be clear

function gen() {
  setTimeout(() => {
    this.result = 'SOMETHING';
  },0);
  return this.result;
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question