What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand?

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

fetchData();

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

Answer №1

Due to the scoping of shipsJSON within the githubUsers function, one solution could be to use await on the returned data in another async function and then iterate through it.

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();
  // write the remaining code here
}

main();

Another approach is possible 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();
  // write the remaining code here
}

main();

Answer №2

When using async function, the githubUsers call may not complete before your foreach loop. Additionally, the shipsJSON variable is declared within the scope of githubUsers, making it unavailable outside of it. To access it in the outer scope, you should use return. Here's how you can do it:

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();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The AddClass function fails to function properly after an ajax form is submitted

I am facing a challenge in setting up validation for my ajax form. My goal is to have a red border appear around the input field if it is submitted empty. Unfortunately, when I try to use addClass(), it does not seem to have any effect. The alert message ...

An error occurred while attempting to decode the JSON object

Encountering an issue while using Google translation to translate the content of a website, resulting in the error message "No JSON object could be decoded." Below is the snippet of the code: import requests from dragnet import extract_content from google ...

Prevent IonContent from scrolling to the bottom or top when using Ionic framework

In my Ionic app, I have a long text page with 2 buttons that trigger the actions scrollToBottom and scrollToTop. Due to the length of the page, I have set the scroll duration to be 30 seconds. I am facing two issues here: How can I stop the scrolling ...

Error in TypeScript: Typography type does not accept 'string' type as valid

As I attempt to implement the Typography component from material-ui using TypeScript, I encounter a perplexing error message TypeScript is throwing an error: Type 'string' is not assignable to type 'ComponentClass<HTMLAttributes<HTMLE ...

Executing a simulated onClick event in jQuery

Attempting to create a simulated onclick event on a drop-down menu has proved challenging for me. An IE object is being used to navigate to a page, where I need to modify a dropdown menu that contains an onchange event: $('select[name="blah"]') ...

I am looking to implement a required alert for a radio button that mimics HTML5. How can

When using the input type text, adding the required attribute prevents the form from submitting and prompts the browser to focus on the required field with an alert instructing to fill it out. On the other hand, when applying the required attribute to t ...

Modifying an object property within a state container array in React using Hooks' useState

As a React beginner, I decided to create a simple Todo app. This app allows users to add tasks, delete all tasks, or delete individual tasks. The Todo Form component consists of an input field and two buttons - one for adding a task and the other for dele ...

Exploring the functionality of event.target.name.value

I've been struggling to make event.target.name.value work for an input field in my form. When I submit the form, the values appear as null and I have to click twice to get them. This is the code I've written: const [name, setName] = useState(& ...

Mastering the Art of jQuery Post with Iteration and Result Utilization

I am facing an issue with my code function fetchInfoFromDB() { let body = ""; let text = ""; $("tr").each(function (index) { let code = $(this).children("td:nth-child(2)"); $.post("http://urltogetdatafromdatabase.com/getinfo.ph ...

Enhancing HTML through Angular 7 with HTTP responses

Sorry to bother you with this question, but I could really use some help. I'm facing an issue with updating the innerHTML or text of a specific HTML div based on data from an observable. When I try to access the element's content using .innerHTM ...

Extracting data from OECD Dataset using Python without any issues with the time period in SDMX-JSON parsing

Currently, I am utilizing the python library pandaSDMX to extract entire datasets from the OECD database and convert them into a CSV format for inclusion in an SQL database. In order to access an OECD dataset in SDMX-Json format, you can simply input a li ...

Extract the value of an HTML tag and store it in a PHP variable

I have successfully implemented JavaScript code to dynamically update the value of an input tag in my popup. However, when I try to echo out this updated value using a PHP variable within the same popup, it doesn't seem to work as expected. Despite un ...

Failure to load image logo when refreshing the page

There's something peculiar happening in my App.vue. Imagine I have a route link, let's say it's localhost/tools or any similar route. The logo image will display on this route. Take a look at the image here https://i.stack.imgur.com/6HaXI.p ...

Why does my ball defy the laws of geometry and refuse to be perfectly round with

I'm attempting to create a simple game in javascript, but I've run into an issue where my circle isn't perfectly round. Despite searching for solutions online for 20 minutes, I haven't been able to resolve the problem. I'm hoping s ...

Removing the JavaScript unicode character 8206 from a text string

I recently transitioned from VB.NET to JavaScript, and I am still getting familiar with the language. I have encountered an issue where a string I'm working with in JavaScript contains Unicode escape characters (0x5206, left-to-right mark) that I need ...

Before displaying the rows stored in the controller, ng-repeat initially displays one row

I am experiencing an issue with my back end service sending data to a $scope variable. I am using this variable to populate rows in a table with ng-repeat. Upon loading the page, initially one row is visible on the browser but then disappears once the loa ...

Retrieving Firestore information as a JavaScript object

I'm working on retrieving data from Google Firestore as a JavaScript object in Vue.js (3). It functions correctly when used within a V-for loop, but I also need to utilize the array in methods. How can I convert the Firestore data into a basic JavaScr ...

Why am I receiving an error message stating "undefined is not a function" when trying

I am attempting to create a popover using the Angular UI pop over feature. I have loaded my HTML and compiled it, but when I run my program and click on the star icon (where I display the popover), I receive an error stating that 'undefined is not a f ...

What is the method by which Morgan middleware consistently displays the output on the console following the execution of all other middleware

Utilizing the express library along with the logging library known as morgan Provided below is a snippet of working code that can be used to reproduce this in nodejs: const express = require('express') const morgan = require('morgan') ...

What are some effective replacements for SoundManager2 worth considering?

While Soundmanager2 is a useful app, many find the code to be overly complex and difficult to navigate. It almost seems as if it was purposely written in a way to confuse rather than clarify. Are there any recommended alternatives to Soundmanager2 that are ...