Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
¿Por qué no obtengo la variable?

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(); })
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!