-1

im trying to let a variable from JSON and use it in other function but I'm doing something wrong can someone help me? the code is`

async function githubUsers() {
  let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d')
  let shipsJSON =  await response.json()
}

githubUsers()



shipsJSON.forEach((item) => {
  item.forEach((nestedItem) => {
    placeCharacter(nestedItem.x, nestedItem.y, "O", myGrid)
    // placeCharacter(nestedItem.x, nestedItem.y, 'O', myGrid);
    placeRandomCharacter('O', enemyGrid, enemyGridSize);
    drawBreak();

  })
zzekron 1
  • 21
  • 1
  • 2
    Because that variable is created in function scope https://stackoverflow.com/a/500459/2930038 – vanowm May 30 '22 at 18:57

2 Answers2

-1

Because shipsJSON is scoped to the githubUsers function. Maybe the best way is to await that returned data within another async function, and then loop over the data.

async function githubUsers() {
  let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d');
  return response.json();
}

async function main() {
  const shipsJSON = await githubUsers();
  // rest of your code
}

main();

Alternatively since fetch returns a promise:

function githubUsers() {
  return fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d');
}

async function main() {
  const response = await githubUsers();
  const shipsJSON = await response.json();
  // rest of your code
}

main();
Andy
  • 61,948
  • 13
  • 68
  • 95
  • There's no need to make gitHubUsers async — since fetch returns already a Promise. In your example an async `main` is quite enough. – Roko C. Buljan May 30 '22 at 19:00
  • I'm well aware of that. I was following the OP's code. Seems like they wanted to separate things out. – Andy May 30 '22 at 19:05
  • So all you've done is replace `async/await` with a promise/then. How is that an improvement? – Andy May 30 '22 at 19:08
-2

You are using async function, so githubUsers call won't complete before your foreach loop. Also, you are declaring shipsJSON variable inside scope of githubUsers, meaning it won't be available outside it. So you should use return to get it to outer scope. Do it like this:

async function githubUsers() {
  let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d')
  return response.json()
}

async function fetchAndLoop() {
    const json = await githubUsers()



    json.forEach((item) => {
      item.forEach((nestedItem) => {
        placeCharacter(nestedItem.x, nestedItem.y, "O", myGrid)
        // placeCharacter(nestedItem.x, nestedItem.y, 'O', myGrid);
        placeRandomCharacter('O', enemyGrid, enemyGridSize);
        drawBreak();

      });
}

fetchAndLoop();
Bruno Polo
  • 657
  • 5
  • 11