如何使用多个函数对获取的结果求和? [英] How to sum the results of a fetch using multiple functions?

查看:94
本文介绍了如何使用多个函数对获取的结果求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与OpenWeatherMapAPI一起计算过去5天的降水量总和.为此,我有5个使用fetch api进行api调用的异步函数.所收到的有关我的数据是跨越24小时周期的每小时历史天气预报数据.完整代码如下.json响应存储到一个常量(Ex. const histData1 )中,然后在其中进行迭代以在给定的24小时内将所有一个值求和.注意:湿度被用作概念证明,因为它已经有一段时间没有下雨了

I am working with OpenWeatherMapAPI to calculate the sum of precipitation for the previous 5 days. To do this I have 5 async functions with api calls using the fetch api. The data received, that concerns me, is the hourly historic weather data spanning a 24 hour period. Full code bellow. The json response is stored to a constant (Ex.const histData1) where it is then iterated through to sum all of one values over that given 24 hour period. Note: humidity is used as a proof of concept because it hasnt rained here in awhile

    for (var i in histData1.hourly){
      total1 += histData1.hourly[i].humidity;
    };

当我将结果值total1发送到控制台时,我收到了预期的结果.尝试将所有这些结果加在一起时,我的麻烦就来了,即合计1 +合计2 +合计3 +合计4 +合计5.我认为可能可行的一种解决方案是在每个函数中返回total [1,2,3,4,5]变量,然后对其求和.例

When I send the resulting value, total1, to the console I receive the expected results. My trouble is coming when trying to add all of these results together i.e. total1 + total2 + total3 + total4 + total5. One solution I thought might work was returning the total[1,2,3,4,5] variable at each function and then summing them. Ex.

var rainTotals = getData1() + getData2() + getData3() + getData4() + getData5()
 console.log(rainTotals)

这将导致以下输出:[object Promise] [object Promise] [object Promise] [object Promise] [object Promise],因此它似乎是数据类型问题.

This resulted in the following output: [object Promise][object Promise][object Promise][object Promise][object Promise] so it appears to be a datatype issue.

任何人都可以从五个单独的功能中得出所有湿度值的总和.随意烤我的代码,这是我的新手.

Can anyone shed light as to adding all of the humidity values up from the five separate functions. Feel free to roast my code, I'm pretty new at this.

谢谢!

//WORKS Provies a json of hourly weather data for (1)24 hr period starting 5 days ago.
  const fiveDaysAgo = Math.floor((Date.now() / 1000)-432000);
  const fivedayURL = "http://api.openweathermap.org/data/2.5/onecall/timemachine?lat=29.8833&lon=-97.9414&dt=" + fiveDaysAgo +"&appid="
  async function getData5(){
    const response5 = await fetch(fivedayURL)
    const histData5 = await response5.json();
    var total5 = 0
    for (var i in histData5.hourly){
      total5 += histData5.hourly[i].humidity;
    };
    console.log(total5);
    return total5;
  }
  getData5();


  const fourDaysAgo = Math.floor((Date.now() / 1000)-345600);
  const fourdayURL = "http://api.openweathermap.org/data/2.5/onecall/timemachine?lat=29.8833&lon=-97.9414&dt=" + fourDaysAgo +"&appid=5ffab1cda2c6b2750c78515f41421805"
  async function getData4(){
    const response4 = await fetch(fourdayURL)
    const histData4 = await response4.json();
    var total4 = 0;
    for (var i in histData4.hourly){
      total4 += histData4.hourly[i].humidity
    };
    console.log(total4);
    return total4;
  }
  getData4();


  const threeDaysAgo = Math.floor((Date.now() / 1000)-259200);
  const threedayURL = "http://api.openweathermap.org/data/2.5/onecall/timemachine?lat=29.8833&lon=-97.9414&dt=" + threeDaysAgo +"&appid=5ffab1cda2c6b2750c78515f41421805"
  async function getData3(){
    const response3 = await fetch(threedayURL);
    const histData3 = await response3.json();
    var total3 = 0;
    for (var i in histData3.hourly){
      total3 += histData3.hourly[i].humidity;
    };
    console.log(total3);
    return total3;
  }
  getData3();

  const twoDaysAgo = Math.floor((Date.now() / 1000)-172800);
  const twodayURL = "http://api.openweathermap.org/data/2.5/onecall/timemachine?lat=29.8833&lon=-97.9414&dt=" + twoDaysAgo +"&appid=5ffab1cda2c6b2750c78515f41421805"
  async function getData2(){
    const response2 = await fetch(twodayURL);
    const histData2 = await response2.json();
    var total2 = 0;
    for (var i in histData2.hourly){
      total2 += histData2.hourly[i].humidity;
    };
    console.log(total2);
    return total2;
  }
  getData2();

  const oneDaysAgo = Math.floor((Date.now() / 1000)-86400);
  const onedayURL = "http://api.openweathermap.org/data/2.5/onecall/timemachine?lat=29.8833&lon=-97.9414&dt=" + oneDaysAgo +"&appid=5ffab1cda2c6b2750c78515f41421805"
  async function getData1(){
    const response1 = await fetch(onedayURL);
    const histData1 = await response1.json();
    var total1 = 0;
    for (var i in histData1.hourly){
      total1 += histData1.hourly[i].humidity;
    };
    console.log(total1);
    return total1;
  }
  getData1();

 var rainTotals = getData1() + getData2() + getData3() + getData4() + getData5()
 console.log(rainTotals)//returns [object Promise][object Promise][object Promise][object Promise][object Promise]

推荐答案

这里发生了几件事.首先,要回答您的问题,因为您的 getDataX 函数被声明为异步函数,所以它们返回Promises,这些Promises最终将使用您要查找的实际值来进行解析或拒绝.

There are a couple things happening here. Firstly, to answer your question, because your getDataX functions are declared asynchronous, they return Promises that will eventually either resolve or reject with the actual values that you're looking for.

在处理Promise时,您需要在所有这些Promise都解决后将总值求和.

When working with Promises, you need sum the total values after all of these promises have resolved.

第二,您的代码有些重复.您会注意到, getDataX 函数的内在函数之间几乎没有什么区别.为了简化这一过程,您可以提取差异作为函数参数,并将所有相同的代码封装在一个函数中.

Second, you have a bit of duplication in your code. You'll notice that there is very little difference between the innards of your getDataX function. To simplify this, you can extract the differences as function parameters, and encapsulate all the same code within one function.

这将导致实现如下所示:

This would result in an implementation like below:

function getDaysAgo(days) {
    return Math.floor((Date.now() / 1000) - (86400 * days))
}

async function getDataForDaysAgo(days) {
    let daysAgo = getDaysAgo(days)
    const apiURL = `http://api.openweathermap.org/data/2.5/onecall/timemachine?lat=29.8833&lon=-97.9414&dt=${daysAgo}&appid=5ffab1cda2c6b2750c78515f41421805`
    const apiResponse = await fetch(apiURL)
    const responseJson = await apiResponse.json()
    var total = 0
    responseJson.hourly.forEach(hour => {
        total += hour.humidity
    });
    console.log(`getDataForDaysAgo(${days}) returns ${total}`)
    return total
}

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

getDataSums().then(result => {
    console.log(result)
})

这篇关于如何使用多个函数对获取的结果求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆