How to sum the results of a fetch using multiple functions?

白昼怎懂夜的黑 提交于 2021-01-29 06:56:46

问题


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

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)

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.

Thanks!

//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]

回答1:


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.

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

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



回答2:


Async functions always returns a promise.

What you can do is to use Promise.all to aggregate them into one array.

Promise.all([getData1(), getData2(), getData3(), getData4(), getData5()]).then((values) => {
  var sum = 0;
  for(var i=0; i<values.length; i++){
    sum += values[i];
  }
  console.log(sum);
});

Source : Async Functions




回答3:


You can use await to get the result of async function.

var rainTotals = await getData1() + await getData2() + await getData3() + await getData4() + await getData5();



回答4:


Async function delays because it wait for await. 'return' give data immediatly so that's why data give empty object(when console.log(getData1()) only empty objects returned). So getding total data should be awaited. 'total' data in each getData function was pushed into an array. Each getData function get await in asyncAll function to log array at once.

// Data array
let arr = [];


//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=5ffab1cda2c6b2750c78515f41421805"
  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);
    await arr.push(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);
    await arr.push(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);
    await arr.push(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);
    await arr.push(total2);
    return total2;
  }

  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);
    
    //Push data after data asynced 
    await arr.push(total1);
    return total1;
  }
  //Moved getData function to asyncAll function.

 var rainTotals = [];
  
  // Awaited for getData functions, logged total data.
 async function asyncAll() {
  await getData1();
  await getData2();
  await getData3();
  await getData4();
  await getData5();
  await console.log(arr.join(', '), 'async');
}

asyncAll();


来源:https://stackoverflow.com/questions/64797333/how-to-sum-the-results-of-a-fetch-using-multiple-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!