0

I have two arrays created outside a method:

let titles1 = [];
var checked1 = [];

async function fetchPosts(titles, checked) {
  try {
    const rawPosts = await fetch("......");
    const posts = await rawPosts.json()
    for (var i = 0; i < posts.length; i++) {
      titles.push(posts[i]["title"]);
      checked.push(posts[i]["checked"]);
    }
    return posts
  } catch (e) {
    console.log("error on getting data: ", e)
  }
}

fetchPosts(titles1, checked1);
console.log(titles1[0])

so the method fetchPosts populates both arrays. However when I do a console log on titles1 and checked1, there is nothing. How can I populate them?

adiga
  • 34,372
  • 9
  • 61
  • 83
chris56tv
  • 147
  • 1
  • 2
  • 10
  • The code you posted looks like it should work, I'd make sure your console log is happening after the data is fetched and not right away, before the data is populated – IrkenInvader Nov 14 '19 at 18:54
  • You need to `await fetchPosts()` as well. If you want to await at the top level, you need to wrap it in an IIFE: `(async function(){ await fetchPosts(titles1, checked1); console.log(titles1[0]) })();` – adiga Nov 14 '19 at 18:58
  • Is there another way to do this without that wrapping? Cause I need those two variables (titles1 and checked1) for more stuff. I have a react component after that that will need those values – chris56tv Nov 14 '19 at 19:01
  • This is how asynchronicity works. Please check the duplicate for more information – adiga Nov 14 '19 at 19:13

0 Answers0