TheBeJIIHiu
@TheBeJIIHiu
Просто обычный кодер?

Почему возвращает Promise { }?

const fetch = require("node-fetch");
async function gen() {
await 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)
        ];
      result = {
        image: postID.data.url,
        category: postID.data.link_flair_text,
        caption: postID.data.title,
        permalink: postID.data.permalink
      };
    });
  return result;
};

console.log(gen())


возвращает Promise { }
61b327dcb0796023287466.jpeg
  • Вопрос задан
  • 69 просмотров
Пригласить эксперта
Ответы на вопрос 2
Lynn
@Lynn
nginx, js, css
Потому что асинхронная функция всегда возвращает Promise
Ответ написан
Комментировать
vabka
@vabka
Токсичный шарпист
Что-то ты намудрил

const fetch = require("node-fetch");
async function gen() {
    await 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)
                ];
            result = {
                image: postID.data.url,
                category: postID.data.link_flair_text,
                caption: postID.data.title,
                permalink: postID.data.permalink
            };
        });
    return result;
};
console.log(gen())


Попробуй так:
const fetch = require("node-fetch");

async function gen() {
  const response = await fetch("https://www.reddit.com/r/memes/hot/.json?count=100");
  const json = await response.json();
  const post = json.data.children[Math.floor(Math.random() * json.data.children.length)];
  return {
        image: post.data.url,
        category: post.data.link_flair_text,
        caption: post.data.title,
        permalink: post.data.permalink
      };
}

gen().then(x=>console.log(x));
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы