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

187
Vistas
Global values not working, can not get value from inside the function. Trying to make values (windspeed, etc) available outside of function

Stuck on this for a couple of days now - still new to JS. I am trying to make the variable's values from inside the function available outside the function. I have tried using global_this and it doesn't work. The values show up fine in the console log and inner HTML - however when I try to use them anywhere else I get undefined.

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 Respuestas
Responde la pregunta

0

I done a quick rewrite of your example.

Nested functions can get you in trouble, I separated them.

For variables to be accessible I just declared them outside the function.

Your function executes, but does not give results immediately, if you want to access variables, you will get 'undefined' until results arrive. If you really need to wait for result, you need to do that in special async function.

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

if you don't need to wait for variables you can use:

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 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