首页 > 解决方案 > 循环获取请求在最后一项之前返回错误

问题描述

我有一个循环,它遍历一组位置并检索数组中位置的当前天气。但由于某种原因,在最后一个请求生效之前,我得到了 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>`;
         })
   }
}

标签: javascript

解决方案


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

并控制台记录国家,以便您可以在浏览器的控制台中检查您在哪些国家/地区出现错误以防止它们发生。


推荐阅读