0

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 can await the >Promise

el-xlrnz
  • 1
  • 1
  • 2
    "nothing is showing" - are you sure you're not seeing a Promise? – Nick Parsons Feb 16 '21 at 07:49
  • Side note: Although this isn't causing an issue, don't use `.map()` for array iteration only. Instead you can return the mapped value, or swap `.map()` for `.forEach()`: [Is performing a mapping operation without using returned value an antipattern?](https://stackoverflow.com/a/56904505) – Nick Parsons Feb 16 '21 at 07:52
  • @nick-parsons Nope, nothing was showed the promise is fulfilled and everything work fine. The only problem is to extract the 'list' out of the function so I can reuse it – el-xlrnz Feb 16 '21 at 07:56
  • 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 can `await` the Promise. – Nick Parsons Feb 16 '21 at 08:11
  • 1
    Thanks man! I've understand now! – el-xlrnz Feb 16 '21 at 11:05
  • Ok, maybe understande but not at all......... ```.then(list => {const x = list[0]})``` if after that I'm tryin to ```console.log(x)``` x is still empty – el-xlrnz Feb 16 '21 at 11:13
  • You need to do the `console.log(x)` inside the arrow function. `.then(list => {const x = list[0]; console.log(x)})` – Nick Parsons Feb 16 '21 at 11:14
  • _"Get the value from a function in some other languages is simple"_ You are comparing synchronous function calls in other languages with asynchronous function calls in JavaScript. Most people saying that have no experience with asynchronous functions in other languages. It's nearly similar in Python and more complex in most other languages. The reason most people are confronted with asynchronous functions in JavaScript is because it's so simple in JavaScript. – Thomas Sablik Feb 16 '21 at 12:38

0 Answers0