如何在后续请求中使用从提取请求返回的数据



我正在尝试显示用户将按名称搜索的城市的天气。我正在使用第一个API允许用户按城市名称进行搜索。这将返回一个包含lat和lon的数据对象,然后我将使用它来运行第二个获取请求,以获取由lat和lon搜索的城市的天气预报。这是我目前编写的代码。

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

在每个then回调中,您应该返回您想要传递的信息,这些信息可以是promise,也可以只是一个值,以避免典型的"回调地狱";。

一旦你有了纬度和经度,就立即用它来做下一个fetch

所以它变成了这个——我删除了你的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);
});   

使用async/await语法:,所有这些都变得更容易

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

最新更新