+ 2

how to set variable from online json file in js

Im trying to save the data from JSON and import it via variable but something is going wrong can someone help? the code is` https://code.sololearn.com/WFAiYEVbF59o

30th May 2022, 6:46 PM
Arthur Vardanyan
Arthur Vardanyan - avatar
3 Answers
+ 1
You're trying to do a lot of pretty complex things all at once. And you can't keep track of it all by now. Try to start from scratch with small steps and tasks. For example, in the beginning only to read and parse a small JSON file and show the result anyhow.
30th May 2022, 8:44 PM
JaScript
JaScript - avatar
0
There are some fundamental wrongs in your script. You are using "let" on "shipsJSON", which is limited to block scope. Meaning, it's not available outside of the brackets. Another issue is that your async function doesn't return anything. Nor is it used properly or used at all. Even if you used a "var" instead of "let", "shipsJSON" would still be "undefined". As the rest of the script is synchronous. The following "forEach" loop will immediately run on the undefined variable, as the asynchronous call stack is only consumed after the synchronous call stack is empty. You will have to call an async function from a synchronous function and use the result in a callback function. The fetch function returns a promise. You could add a callback function using the "then" function of the promise object.
30th May 2022, 8:49 PM
Mustafa A
Mustafa A - avatar
0
You can solve the current problem by removing the async function at the top and replacing the following forEach loop with this. fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d').then(res => res.json()).then(ships => ships.forEach((item) => { item.forEach((nestedItem) => { placeCharacter(nestedItem.x, nestedItem.y, "O", myGrid) // placeCharacter(nestedItem.x, nestedItem.y, 'O', myGrid); placeRandomCharacter('O', enemyGrid, enemyGridSize); drawBreak(); }) })) Look up and study how the fetch function works. Also, how to use promises and the relation between promises and async functions.
30th May 2022, 8:55 PM
Mustafa A
Mustafa A - avatar