javascript - 循环获取请求在最后一项之前返回错误
问题描述
我有一个循环,它遍历一组位置并检索数组中位置的当前天气。但由于某种原因,在最后一个请求生效之前,我得到了 TypeError: Cannot set property 'innerHTML' of null。
而之前所有的都正常工作。真的不知道为什么这里会出错。
const getData = () => {
for (const country in weatherCountries) {
console.log(country);
fetch(`${baseUrl}?lat=${weatherCountries[country].lat}&lon=${weatherCountries[country].long}&APPID=${appId}`)
.then(res => res.json())
.then(data => {
conditions = data.weather[0].main;
temperature = data.main.temp - 273.15;
temperature = Math.round(temperature);
document.getElementById(weatherCountries[country].name).innerHTML = `<h5>Current Weather</h5>
<table>
<tr><th>Conditions:</th><th>Temperature:</th></tr>
<tr><td>${conditions}</td><td>${temperature}</td></tr>
</table>`;
})
}
}
解决方案
用 if 条件检查元素,这样如果国家不在页面中,它就不会崩溃并继续下一个国家:
let countryElement = document.getElementById(weatherCountries[country].name);
if (countryElement) {
countryElement.innerHTML = `<h5>Current Weather</h5>
...
} else {
console.log('The country: ' + country + ' is not found');
}
并控制台记录国家,以便您可以在浏览器的控制台中检查您在哪些国家/地区出现错误以防止它们发生。
推荐阅读
- rest - 使用 sipgate Rest API 发布语音邮件问候语
- python - 如何在特定时间之间获取记录?
- flutter - 减小 NavigationRailDestination Tiles 的大小
- angular - 使用德语语言环境的 MatDatepicker 无法正常工作。也许是错误?
- database-design - 如果表要满足 1NF,列值可以包含空格吗?
- python-3.x - 如何使用服务原则作为默认身份验证机制在 Azure DevOps CI 管道中运行 pytest(单元测试)
- php - Mysql 在发送快速请求时返回相同的行
- javascript - 我如何禁用标签成员
- tensorflow - ML.NET/AI 读取文档/文档分割
- redux - 如何在 redux 中执行依赖异步调用?