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

184
Views
Los valores globales no funcionan, no se puede obtener valor desde dentro de la función. Tratando de hacer que los valores (velocidad del viento, etc.) estén disponibles fuera de la función

Atrapado en esto durante un par de días, todavía nuevo en JS. Estoy tratando de hacer que los valores de la variable desde dentro de la función estén disponibles fuera de la función. He intentado usar global_this y no funciona. Los valores aparecen bien en el registro de la consola y en el HTML interno; sin embargo, cuando trato de usarlos en cualquier otro lugar, no estoy definido.

 enter code here function x() {fetch('http://api.openweathermap.org/data/2.5/weather? lat=33.778726&lon=-118.377751&appid=c8ba55aeb3b4aeb0add9badde352f0df&units=imperial') .then( response => response.json()) .then( data => openweather(data)) .catch( err => console.log(err)) console.log("hack") function openweather(data) { swamprat = Object.values(data) windspeed = data.wind.speed; winddegree = data.wind.deg; airtemp = data.main.temp; airpressure = data.main.pressure; knots= (windspeed * 0.868976); windspeed = parseInt(windspeed); winddegree = parseInt(winddegree); airtemp = parseInt(airtemp); airpressure = parseInt(airpressure) knots= parseInt(knots); console.log("Wind Speed: " + windspeed) console.log("Wind Direction: " + winddegree) console.log("Temperature: " + airtemp) console.log("Air Pressure: " + airpressure) console.log("Knots: " + knots); document.getElementById("windspeedx").innerHTML = [windspeed] document.getElementById("winddirectionx").innerHTML = [winddegree] document.getElementById("airtemperaturex").innerHTML = [airtemp] document.getElementById("airpressurex").innerHTML = [airpressure] document.getElementById("knotsx").innerHTML = [knots] } } console.log(windspeed) x() setInterval(x,15000)
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Hice una reescritura rápida de tu ejemplo.

Las funciones anidadas pueden meterte en problemas, las separé.

Para que las variables sean accesibles, simplemente las declaré fuera de la función.

Su función se ejecuta, pero no da resultados inmediatamente, si desea acceder a las variables, obtendrá 'indefinido' hasta que lleguen los resultados. Si realmente necesita esperar el resultado, debe hacerlo en la función asíncrona especial.

 let windspeed; let winddegree; let airtemp; let airpressure; let knots; function openweather(data) { windspeed = data.wind.speed; winddegree = data.wind.deg; airtemp = data.main.temp; airpressure = data.main.pressure; knots= (windspeed * 0.868976); windspeed = parseInt(windspeed); winddegree = parseInt(winddegree); airtemp = parseInt(airtemp); airpressure = parseInt(airpressure) knots= parseInt(knots); console.log("Wind Speed: " + windspeed) console.log("Wind Direction: " + winddegree) console.log("Temperature: " + airtemp) console.log("Air Pressure: " + airpressure) console.log("Knots: " + knots); document.getElementById("windspeedx").innerHTML = [windspeed] document.getElementById("winddirectionx").innerHTML = [winddegree] document.getElementById("airtemperaturex").innerHTML = [airtemp] document.getElementById("airpressurex").innerHTML = [airpressure] document.getElementById("knotsx").innerHTML = [knots] } async function x(){ await fetch('https://api.openweathermap.org/data/2.5/weather?lat=33.778726&lon=-118.377751&appid=c8ba55aeb3b4aeb0add9badde352f0df&units=imperial') .then( response => response.json()) .then( function(data){ openweather(data); setTimeout(x,15000); }) .catch( err => console.log(err)); } async function start(){ await x(); console.log( "TEST: " + windspeed ); } start();

si no necesita esperar variables, puede usar:

 function x(){ fetch('https://api.openweathermap.org/data/2.5/weather?lat=33.778726&lon=-118.377751&appid=c8ba55aeb3b4aeb0add9badde352f0df&units=imperial') .then( response => response.json()) .then( function(data){ openweather(data); setTimeout(x,15000); }) .catch( err => console.log(err)); } x(); console.log( "TEST: " + windspeed ); // will get undefined at first
about 4 years ago · Santiago Trujillo 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!