Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
¿Cómo funciona la configuración de variables con await?

¿Puede alguien explicarme por qué esto no funciona de la manera que esperaba?

Espero que se ejecute el último archivo console.log después de ejecutar mis funciones, pero devuelve una cadena de longitud vacía en lugar de la fecha real.

Estas son las variables que quiero establecer después de mi llamada de función. Declarándolos ahora para que el alcance se establezca globalmente.

 var seasonStart = ''; var seasonID = '';

Esta función obtiene mis datos json. Tengo la URL declarada arriba en mi código, está devolviendo todo como se esperaba.

 async function getCurrentSeasonapi(url) { //store response const response = await fetch(url); //store data in JSON var data = await response.json(); //I tried to set the variables here but it didn't work so I tried using a separate function setSeasonInfo(data); }

La función que se llama arriba:

 //set current season function setSeasonInfo(data) { seasonStart = data.seasons[0].regularSeasonStartDate; seasonID = data.seasons[0].seasonId; //this returns the correct date console.log(seasonStart); }

llamando a la función, por lo que mis variables deberían configurarse correctamente después de que se ejecute esta función

 getCurrentSeasonapi(getCurrentSeasonURL); //this is returning '' instead of the actual date set in the function console.log(seasonStart);

Estoy pensando que esto es un problema de alcance, pero no estoy seguro de por qué. Aquí hay un ejemplo en el que estaba probando el alcance. Así es como esperaba que se ejecutara mi código:

 var test = 1; async function changeTest() { test =100; } document.getElementById("first").innerHTML = test + `<br>` + 'Run Function:' + `<br>`; changeTest(); document.getElementById("first").innerHTML += test
 <html> <body> <p> testing JS execution</p> <div id = 'first'> </div> </body> </html>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

No estás esperando la llamada. El código de ejemplo debe tener una promesa.

 var testSync = 1; var testAsync = 1; async function changeTest() { testSync = 100; await new Promise((resolve, reject) => { setTimeout(() => { testAsync = 100; resolve(); }, 300); }); } document.getElementById("first").innerHTML = `${testSync} - ${testAsync} <br> Running <br>`; changeTest(); document.getElementById("first").innerHTML += `${testSync} - ${testAsync}`
 <html> <body> <p> testing JS execution</p> <div id='first'> </div> </body> </html>

Ahora con ella esperando la llamada

 var testSync = 1; var testAsync = 1; async function changeTest() { testSync = 100; await new Promise((resolve, reject) => { setTimeout(() => { testAsync = 100; resolve(); }, 300); }); } (async function() { document.getElementById("first").innerHTML = `${testSync} - ${testAsync} <br> Running <br>`; await changeTest(); document.getElementById("first").innerHTML += `${testSync} - ${testAsync}` }());
 <html> <body> <p> testing JS execution</p> <div id='first'> </div> </body> </html>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda