Get the value from a function in some other languages is simple like write return something
I can't get how to do it in JS from an async function.
const URL = `https://www.reddit.com/r/all.json`;
async function getPost() {
var list = [];
let response = await fetch(URL).then((res) => res.json());
let childList = await response.data.children;
childList.map((el) => {
let id = el.data.id;
let title = el.data.title;
list.push({
id: id,
title: title,
});
});
console.log(list);
}
var oo = getPost();
If you try the code like this everything work fine. But if to change console.log(list)
inside getPOst()
to return list
and try to console.log(oo)
nothing is showing
So... BIG thanks to @nick-parsons
that's the answer:
Oh, so a Promise is being shown. Your
async
function will wrap the >return
value in a Promise, so that's expected. To "extract" the >value/list, you need to use.then(list => // use list here)
on the >returned Promise. Or, if you're in a ES module, you canawait
the >Promise