Javascript 如何使用多个函数求取结果的和?
我正在使用OpenWeatherMapAPI计算前5天的降水总量。要做到这一点,我有5个异步函数,使用fetchapi调用api。我关心的是,收到的数据是24小时内每小时的历史天气数据下面的完整代码。json响应被存储到一个常量(例如,Javascript 如何使用多个函数求取结果的和?,javascript,asynchronous,async-await,fetch-api,arcgis-js-api,Javascript,Asynchronous,Async Await,Fetch Api,Arcgis Js Api,我正在使用OpenWeatherMapAPI计算前5天的降水总量。要做到这一点,我有5个异步函数,使用fetchapi调用api。我关心的是,收到的数据是24小时内每小时的历史天气数据下面的完整代码。json响应被存储到一个常量(例如,const histData1)中,然后在该常量中对其进行迭代,以对给定24小时内的所有一个值求和注意:湿度被用作概念证明,因为这里已经有一段时间没有下雨了 for (var i in histData1.hourly){ total1 +=
const histData1
)中,然后在该常量中对其进行迭代,以对给定24小时内的所有一个值求和注意:湿度被用作概念证明,因为这里已经有一段时间没有下雨了
for (var i in histData1.hourly){
total1 += histData1.hourly[i].humidity;
};
当我将结果值total1发送到控制台时,我会收到预期的结果。
我的问题是,当尝试将所有这些结果相加时,即total1+total2+total3+total4+total5。
我认为可行的一种解决方案是在每个函数中返回[1,2,3,4,5]变量的总和,然后对它们求和。前
var rainTotals = getData1() + getData2() + getData3() + getData4() + getData5()
console.log(rainTotals)
这导致了以下输出:[object Promise][object Promise][object Promise][object Promise][object Promise],因此它似乎是一个数据类型问题
有谁能解释一下从五个不同的功能中增加所有湿度值的原因吗。请随意修改我的代码,我对这方面还很陌生
谢谢
//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]
异步函数总是返回一个承诺 您可以使用Promise.all将它们聚合到一个数组中
Promise.all([getData1()、getData2()、getData3()、getData4()、getData5())。然后((值)=>{
var总和=0;
for(var i=0;i异步函数总是返回一个承诺
您可以使用Promise.all将它们聚合到一个数组中
Promise.all([getData1()、getData2()、getData3()、getData4()、getData5())。然后((值)=>{
var总和=0;
对于(var i=0;i您可以使用await
获得async
函数的结果
var rainTotals = await getData1() + await getData2() + await getData3() + await getData4() + await getData5();
您可以使用wait
获取async
函数的结果
var rainTotals = await getData1() + await getData2() + await getData3() + await getData4() + await getData5();
这里发生了两件事。首先,为了回答您的问题,因为您的getDataX
函数被声明为异步的,所以它们返回的承诺最终将解决或拒绝您所寻找的实际值
在处理承诺时,您需要在所有这些承诺都解决后求和总值
其次,您的代码中有一些重复。您会注意到getDataX
函数内部的差异非常小。为了简化此过程,您可以将差异提取为函数参数,并将所有相同的代码封装在一个函数中
var rainTotals = await getData1() + await getData2() + await getData3() + await getData4() + await getData5();
这将导致实现如下所示:
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)
})
这里发生了两件事。首先,为了回答您的问题,因为您的getDataX
函数被声明为异步的,所以它们返回的承诺最终将解决或拒绝您所寻找的实际值
在处理承诺时,您需要在所有这些承诺都解决后求和总值
其次,您的代码中有一些重复。您会注意到getDataX
函数内部的差异非常小。为了简化此过程,您可以将差异提取为函数参数,并将所有相同的代码封装在一个函数中
var rainTotals = await getData1() + await getData2() + await getData3() + await getData4() + await getData5();
这将导致实现如下所示:
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)
})
异步函数延迟是因为它等待等待。“return”立即提供数据,所以这就是为什么数据提供空对象(当console.log(getData1())仅返回空对象时)。因此,应等待getding total data。每个getData函数中的“total”数据被推送到一个数组中。每个getData函数在asyncAll函数中获取Wait以立即记录数组
//数据数组
设arr=[];
//WORKS提供5天前开始的(1)24小时内每小时天气数据的json。
const fiveDaysAgo=数学楼层((Date.now()/1000)-432000);
常数fivedayURL=”http://api.openweathermap.org/data/2.5/onecall/timemachine?lat=29.8833&lon=-97.9414&dt=“+fiveDaysAgo+”&appid=5ffab1cda2c6b2750c78515f41421805”
异步函数getData5(){
const response5=等待获取(fivedayURL)
const histData5=wait response5.json();
var total5=0
对于(histData5中的var i.小时){
total5+=histData5.小时[i].湿度;
};
控制台日志(总计5);
等待到达推送(总计5);
返回总数5;
}
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”
异步函数getData4(){
const response4=等待获取(fourdayURL)
const histData4=wait response4.json();
var total4=0;
对于(histData4中的var i.小时){
total4+=histData4.每小时[i].湿度
};
控制台日志(total4);
等待arr.push(总计4);
返回总数4;
}
getData4();
const threeDaysAgo=Math.floor((Date.now()/1000)-259200);
常量三天URL=”http://api.openweathermap.org/data/2.5/onecall/timemachine?lat=29.8833&lon=-97.9414&dt=“+threeDaysAgo+”&appid=5ffab1cda2c6b2750c78515f41421805”
异步函数getData3(){
const response3=等待获取(三天URL);
const histData3=wait response3.json();
var total3=0;
对于(histData3中的var i.小时){
total3+=histData3.小时[i].湿度;
};
控制台日志(total3);
等待arr.push(总计3);
返回总数3;
}
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”
异步函数getData2(){
const response2=等待获取(twodayURL);
const histData2=wait response2.json();
var total2=0;