I am getting an error I do not understand. I'm fetching an API url in json format, followed by a json to JS object parsing, using json()
const response = fetch('https://power.larc.nasa.gov/api/temporal/monthly/point?parameters=ALLSKY_SFC_SW_DNI&community=RE&longitude=48.0000&latitude=27.0000&format=JSON&start=2001&end=2020');
const data = response.json();
Can someone please explain this error..
fetch
is an asynchronous function; it doesn't return the response right away (you get a Promise
instead).
If you want to fetch the data, you need to use the await
(if the fetch is called inside another async
function), or provide a callback via then
method in the Promise
from the fetch
call:
fetch('https://power.larc.nasa.gov/api/temporal/monthly/point?parameters=ALLSKY_SFC_SW_DNI&community=RE&longitude=48.0000&latitude=27.0000&format=JSON&start=2001&end=2020')
.then(response => {
const data = response.json();
});
If you would do something like this, it won't work:
let data;
fetch('https://power.larc.nasa.gov/api/temporal/monthly/point?parameters=ALLSKY_SFC_SW_DNI&community=RE&longitude=48.0000&latitude=27.0000&format=JSON&start=2001&end=2020')
.then(response => {
data = response.json();
});
console.log(data);
The reason is because the callback inside the then
method is executed after the response has been returned (this might take seconds for example), but the console.log(data)
is executed immediately after the fetch
is called. This means that the data isn't assigned yet and will be probably undefined
. For this reason, if you want to put data
somewhere, you need to put your code inside the callback.
function processData(responseData) {
// Here, you can put your code to process the data from response
console.log(responseData);
}
fetch('https://power.larc.nasa.gov/api/temporal/monthly/point?parameters=ALLSKY_SFC_SW_DNI&community=RE&longitude=48.0000&latitude=27.0000&format=JSON&start=2001&end=2020')
.then(response => {
const data = response.json();
processData(data);
});
This way the data
will be processed after it is fetched.