fetch("http://api.openweathermap.org/data/2.5/weather?lat=17.3764&lon=78.5579&units=Imperial&appid=3f7074e9bd977fa42d82638b27b4560b")
.then((response) =>{
// console.log("text: ",response.json)
return response.json()
})
.then((data)=>{
console.log("data:",data.coord)
var sunrise = data.sys.sunrise
// console.log(sunrise)
var weather = data.weather
var para = document.querySelector('p')
for(i in weather){
para.innerHTML = weather[i].description
}
})
.catch()
console.log(sunrise)
can any one help me why it is giving error as: sunrise is not declared ? my claim is when i declare a varibale as var it should be global. please help me
Hello! Welcome to the community
!
When you declare variables with var
they are declared at the function scope, not at the global scope (unless you declare it at the top of the file). You could make it global if you remove the var
or assign it to the window
object directly: window.sunrise = ...
, but that’s discouraged.
Nevertheless, it will not work as (I think) you expect, since the console.log
will execute before there’s a value assigned to the sunrise
variable. When you use a Promise or asynchronous based call, the execution of the script continues regardless, in other words, it doesn’t stop to wait for the result.
1 Like
even though i declared sunrise
as global it is still not working.
it says undefined
Yes, that’s what I meant by this:
When you use a Promise or asynchronous based call, the execution of the script continues regardless, in other words, it doesn’t stop to wait for the result
You have to log the result inside the callback where the variable is initialized (or assigned a value).
You could cheat if you write something like this:
const handle = setTimeout(function() {
console.log(sunrise);
clearTimeout(handle);
}, 2000);
Which will wait 2 seconds and then log the value to the console. This is discouraged though, so do it only for testing/learning.
Edit: using a timeout is not guaranteed to work. What I wrote is assuming the call to the API (http://api.openweathermap.org) will resolve the data in less than 2 seconds, so if it takes more than 2 seconds it will still log undefined
.