【问题标题】:How to access weather API rain data with async function如何使用异步功能访问天气 API 降雨数据
【发布时间】:2021-03-11 03:01:59
【问题描述】:

我正在使用 OpenWeatherMap API 来计算前 5 天的降水量总和。我在访问湿度或温度等值时没有问题,但我在汇总前 5 天的所有降雨值时遇到了问题。雨仅在实际测量的对象响应中可用。以下是测量下雨时的示例:

您可以看到每小时下雨。18.rain['1h']。 我的问题在于将它们全部汇总。

这是我的完整代码:

//converts current unix date from miliseconds to seconds and subtracts seconds from variable daysAgo
function getDaysAgo(days) {
    return Math.floor((Date.now() / 1000) - (86400 * days)) //returns date of privious 5 days from now.
}
//fetchs historic hourly weather data for rain.
async function getDataForDaysAgo(days) {
    let daysAgo = getDaysAgo(days) //nest getDaysAgo function to variable
    const apiURL = `http://api.openweathermap.org/data/2.5/onecall/timemachine?lat=29.8833&lon=-97.9414&dt=${daysAgo}&appid=` //calls historic weather api using privious days
    const apiResponse = await fetch(apiURL)  //fetch data
    const responseJson = await apiResponse.json() //converts data to json
    var total = 0
    console.log(responseJson);

    responseJson.hourly.forEach(hour => { //loops through each 1hr record of 24
          //if no rain is recorded, rain data is not available. system reprots: NaN
          if (isNaN(hour.rain['1h'])){
            hour.rain['1h'] = 0   //if rain is NaN, change that value to 0.
          }//else(total += hour.rain);
          else{
            total += hour.rain['1h']
          }//otherwise sum all available rain values.
          //total += hour.rain

    });
    console.log(`getDataForDaysAgo(${days}) returns ${total}`) //logs total rain values for each 24hr period
    return total
}
//call above fetch function with appropriate historic 'daysAgo'
async function getDataSums() {
    var data1 = await getDataForDaysAgo(5)
    var data2 = await getDataForDaysAgo(4)
    var data3 = await getDataForDaysAgo(3)
    var data4 = await getDataForDaysAgo(2)
    var data5 = await getDataForDaysAgo(1)
    return data1 + data2 + data3 + data4 + data5; //returns sum of 5 day rain values
}

getDataSums().then(result => { //waits for getDataSums and return result
    var totalRainInches = parseFloat((result)*25.4); //converts to mm to inches
      document.getElementById('precip5day').innerHTML = "Five Day Precipication Accumulation:"
      document.getElementById('precipValue').innerHTML = totalRainInches.toFixed(2) + "″"
    //proof of concept conditional statment that gives recommendations for trail use
    //based on 5 day rain totals and writes to index.html file
    if (totalRainInches <= 0.50){
      document.getElementById('conditions').innerHTML = "Hiking and mountain biking should be okay"
    } else if (totalRainInches < 3 ){
      document.getElementById('conditions').innerHTML = "Due to recent rain activity, use best judgement when hiking or mountain biking"
    } else if (totalRainInches > 7 ){
      document.getElementById('conditions').innerHTML = "Due to heavy rainfall, trails should not be used"
    }else {
      document.getElementById('conditions').innerHTML = "Something broke :("
    }
});

我很幸运将所有湿度值加起来:

    responseJson.hourly.forEach(hour => {
         
          if (isNaN(hour.humidity)){
            hour.humidity = 0   
          }
          else{
            total += hour.humidity
          }

但是当谈到雨值时,我空手而归,并收到错误消息,即雨变量未定义。任何想法?谢谢! 另外,这里有一个指向 previous question 的链接,它让我走到了这一步。

【问题讨论】:

    标签: javascript asynchronous async-await fetch-api arcgis-js-api


    【解决方案1】:

    您确定rain 出现在从 0 到 23 的所有时间吗?如果它丢失了,你会得到"Uncaught TypeError: Cannot read property '1h' of undefined",就像我下面的示例一样。如果你检查它,它应该总结得很好。

    // prep 24 hours with rain and humidity
    var hourly = []
    for (let i = 0; i < 24; i++) {
      hourly[i] = {
        rain: {
          '1h': 0.5
        },
        humidity: 2.2
      }
    }
    
    // your code in a function
    function sumRain(hourly) {
      var total = 0;
      hourly.forEach(hour => {
        // uncomment the next line to check for 'rain' being present
        // if (hour.rain)
        if (isNaN(hour.rain['1h'])) {
          hour.rain['1h'] = 0
        } else {
          total += hour.rain['1h']
        }
      });
    
      return total;
    }
    
    console.log(sumRain(hourly))
    
    // modify hourly so rain is missing from one of the hours
    delete hourly[11].rain;
    
    // now sumrain throws an exception unless you check for hour.rain being present before trying to sum it up
    console.log(sumRain(hourly))

    【讨论】:

    • 看来我想多了。谢谢,现在完美运行!
    猜你喜欢
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2020-06-07
    相关资源
    最近更新 更多