我试图将两个承诺链接在一起,这将使我能够从开放的天气地图API中获取当前天气并将其显示在Carddiv上。这部分我已经按预期运行,但在此情况下,我还想显示5天的天气。我试图将这两个获取请求链接起来,这样当用户进入一个城市时,当前天气将继续显示在我的应用程序中间的Carddiv上,该周的天气将显示在底部。然而,这是我第一次尝试将API的承诺链接在一起,以实现一个有凝聚力的函数,目前我对这个特定的概念还不够了解,不知道分解在哪里。我知道异步等待,但因为我的整个项目都包含在weather中{我不确定在这种情况下如何使用异步等待的语法。根据我现在的情况,即使它在运行,它也只是很多。但我注意到的主要问题是,执行data.weekWeatherUrl会使URL不可访问(使其声明但不读取(,而执行相反的操作会使数据以相同的方式访问。
JavaScript:
weatherData = {
getWeatherInfo: function (city) {
const currentWeatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${currentWeatherApiTag}`;
const weekWeatherUrl = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&units=imperial&appid=${weekForecastApiTag}`;
fetch(currentWeatherUrl)
.then(function(response) {
return response.json();
})
.then(function (data) {
return fetch(data.weekWeatherUrl)
})
.then(function(response) {
return response.json();
})
.then(function(data) {
this.unveilWeather(data);
},
unveilWeather: function (data) {
const {name} = data;
const {icon} = data.weather[0];
const {description} = data.weather[0];
const {temp} = data.main;
const {humidity} = (data.main);
const {speed} = data.wind;
console.log(name, icon, description, temp, humidity, speed);
document.querySelector("#City").innerText = "Weather in " + name;
document.querySelector(".weather-icon").src =`http://openweathermap.org/img/wn/${data.weather[0].icon}.png`;
document.querySelector("#CityWeatherDescription").innerText = description;
document.querySelector("#Temperature").innerText = temp + " °F";
document.querySelector (".humidity-weather-stat").innerText = "Humidity : " + humidity + "%";
document.querySelector(".wind-speed-weather-stat").innerText = "Wind Speed : " + speed + "m/hr";
},
searchCurrentWeather: function () {
this.getCurrentWeatherInfo(document.querySelector("#Search-Bubble").value);
},
};
document.getElementById("SearchBtn").addEventListener("click", function () {
weatherData.searchCurrentWeather();
});
document.getElementById("Search-Bubble").addEventListener("keyup", function (event) {
if (event.key === "Enter") {
weatherData.searchCurrentWeather();
}
});
weatherData.getCurrentWeatherInfo("Brooklyn");
我是编码和自学工作的新手
谢谢!
您想要使用的是Promise.all((
const fetchCurrWeather = fetch(currentWeatherUrl)
.then(function(response) {
return response.json();
});
const fetchWeekWeather = fetch(weekWeatherUrl)
.then(function(response) {
return response.json();
});
Promise.all([fetchCurrWeather, fetchWeekWeather])
.then(function(weatherData) {
// Show current weather
this.unveilWeather(weatherData[0]);
// Show Weekly Weather
for(const day in weatherData[1].list) {
this.unveilWeather(day);
}
});