I am trying to display the weather for the city that a user will search by name. i am using the first API to be allow the user to search by city name. that will return a data object with the lat and lon that i will then use to run a second fetch request to get the weather forecast for the coty searched by lat and lon. this is my current code i have worked up.
var citySearch = function() {
inputFormEl = document.getElementById("city").value;
const apiCall = `https://api.openweathermap.org/data/2.5/weather?&q=` + inputFormEl + apiKey;
fetch(apiCall)
.then(function(response) {
response.json()
.then(function(data) {
console.log(data);
var lat = data.coord.lat;
var lon = data.coord.lon;
getCity(data)
})
}).then(function() {
var secCall = `https://api.openweathermap.org/data/2.5/onecall?lat=${Lat}&lon=${Lon}&appid=087ab696412a7356255185b8f55d9574`;
fetch(secCall)
console.log(secCall);
})
}
Inside each then callback you should return the information you want to pass on -- which can be a promise, or just a value -- so to avoid the nesting that is typical for "callback hell".
And once you have the latitude and longitude, just immediately use that for doing your next fetch.
So it becomes this -- I removed your appid:
fetch(apiCall)
.then(function (response) {
return response.json();
}).then(function (data) {
console.log(data);
getCity(data);
let {lat, lon} = data.coord;
// Just continue...
var secCall = `https://api.openweathermap.org/data/2.5/onecall?lat=${Lat}&lon=${Lon}&appid=....`;
console.log(secCall);
return fetch(secCall);
}).then(function (response) {
return response.json();
}).then(function (data) {
console.log(data.current.weather[0].description);
});
All this is easier with async/await syntax:
(async function() {
let response = await fetch(apiCall);
let data = await response.json();
console.log(data);
getCity(data);
let {lat, lon} = data.coord;
var secCall = `https://api.openweathermap.org/data/2.5/onecall?lat=${Lat}&lon=${Lon}&appid=....`;
console.log(secCall);
let response2 = await fetch(secCall);
let data2 = await response2.json();
console.log(data2.current.weather[0].description);
})();