【发布时间】:2020-08-29 16:02:27
【问题描述】:
我还在开始编程,我对我的异步函数有点困惑。
我正在尝试从我的 firebase 实时数据库中获取最后一天的最后数据,正如您在函数内的 console.log 中看到的那样,我得到了它
但是,当我尝试从函数中返回此值时,它会附带最后一天的所有数据。
在我的实时 firebase 数据库中是这样的:
我的功能是:
public async findLatestWeatherStationRecord(): Promise<WeatherStation> {
const RefR = database.ref('Prototipo0/Leitura/');
const latestWeatherStationRecord = await RefR.limitToLast(1).once(
'value',
snapshot => {
snapshot.forEach(child => {
database
.ref(`Prototipo0/Leitura/${child.key}`)
.limitToLast(1)
.once('value', snapshot => {
snapshot.forEach(childSnapshot => {
const lastMeasurements = childSnapshot.val();
console.log(lastMeasurements);
return lastMeasurements;
});
});
});
},
);
// console.log(latestWeatherStationRecord.val());
return latestWeatherStationRecord;
}
函数内console.log的结果如下:
{
anemometro: 2.8,
bh1750Luminosidade: 1185,
bmp280Altitude: 653.58,
bmp280Pressao: 94739,
csmsv12Solo: 40.76,
dht22Temperatura: 27.9,
dht22Umidade: 31.7,
mhrdMolhamento: -0.04,
pluviometro: 0,
timestamp: 1598554509834,
uvm30aIndiceUv: 1
}
我现在很头疼,因为这个函数的返回结果与函数内部的返回结果不同(console.log)。它返回当天的所有数据,而不是函数的最后一个数据
...,
'-MFlG2p4zMPCC7iQ6Y1D': {
anemometro: 3.73,
bh1750Luminosidade: 1187,
bmp280Altitude: 653.27,
bmp280Pressao: 94742,
csmsv12Solo: 40.81,
dht22Temperatura: 28,
dht22Umidade: 32.5,
mhrdMolhamento: -0.04,
pluviometro: 0,
timestamp: 1598554389829,
uvm30aIndiceUv: 1
},
'-MFlGHWOxi16Qc2HEPba': {
anemometro: 2.8,
bh1750Luminosidade: 1184,
bmp280Altitude: 653.72,
bmp280Pressao: 94737,
csmsv12Solo: 40.79,
dht22Temperatura: 27.9,
dht22Umidade: 31.6,
mhrdMolhamento: -0.04,
pluviometro: 0,
timestamp: 1598554450009,
uvm30aIndiceUv: 1
},
'-MFlGW78ZQcHJ8reA0YD': {
anemometro: 2.8,
bh1750Luminosidade: 1185,
bmp280Altitude: 653.58,
bmp280Pressao: 94739,
csmsv12Solo: 40.76,
dht22Temperatura: 27.9,
dht22Umidade: 31.7,
mhrdMolhamento: -0.04,
pluviometro: 0,
timestamp: 1598554509834,
uvm30aIndiceUv: 1
}
}
}
我想知道为什么函数内部的返回与函数外部不一样。 我希望函数内部的最终结果是相同的。 谁能给我一盏灯?
编辑 - 再次抱歉,我的功能是这样的
public async findLatestWeatherStationRecord(): Promise<WeatherStation> {
const Ref = database.ref('Prototipo0/Leitura/');
const snapshot = await Ref.limitToLast(1).once('value');
let latestWeatherStationRecord;
snapshot.forEach(child => {
database
.ref(`Prototipo0/Leitura/${child.key}`)
.limitToLast(1)
.once('value', snapshot => {
snapshot.forEach(childSnapshot => {
latestWeatherStationRecord = childSnapshot.val();
// console.log(latestWeatherStationRecord);
return latestWeatherStationRecord;
});
});
});
console.log(latestWeatherStationRecord);
// I need to return the snapshot function, but I can't
return latestWeatherStationRecord;
}
【问题讨论】:
-
在 Stack Overflow 上,不要显示文本和代码的图片。将文本复制到问题本身并设置格式,以便于阅读、复制和搜索。
-
对不起,我觉得现在好多了。
标签: typescript firebase-realtime-database async-await