estoy tratando de dejar una variable de JSON y usarla en otra función, pero estoy haciendo algo mal, ¿alguien puede ayudarme? el codigo es`
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(); })Debido a que shipsJSON tiene como alcance la función githubUsers. Tal vez la mejor manera es await los datos devueltos dentro de otra función async y luego recorrer los datos.
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(); Alternativamente, ya que fetch devuelve una promesa:
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();Está utilizando la función asíncrona, por lo que la llamada de githubUsers no se completará antes de su bucle foreach. Además, está declarando la variable shipsJSON dentro del alcance de githubUsers , lo que significa que no estará disponible fuera de él. Por lo tanto, debe usar return para llevarlo al alcance externo. Hazlo asi:
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();