我有一个承诺,可以从我的Firebase实时数据库中检索条目,并使用回调检查特定条目是否在今天的日期进行。当我将其移至promise中时,回调函数(不在promise中起作用)会导致以下错误:
TypeError:无法读取null的属性'checkIfEntryFromToday'
我尝试将.this绑定到构造函数中的函数,但这无济于事。
代码如下:
调用诺言的主要功能
getUsersHydration(){
return new Promise (resolve => {
const ref = this.props.firebase.db.ref(this.state.user)
ref.on("value",function(snapshot){
const userObject = (snapshot.val());
//pull ounces out of object and checks if the entry was made today
const dailyOunces = []
for (const key in userObject) {
let currentVal = userObject[key].ounces
let dateOfEntry = userObject[key].date
if (this.checkIfEntryFromToday(dateOfEntry)){
dailyOunces.push(currentVal)
}
}
//sums the total ounces
const sum = dailyOunces.reduce(function(a,b) { return a + b; },0)
resolve(sum)
},function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
})
}
函数checkIfEntryFromToday会产生错误
checkIfEntryFromToday(milsToEvaluate){
const dayOfEntry = this.findDayByMils(milsToEvaluate)
const today = this.findDayByMils(new Date())
if (dayOfEntry === today) {
return true
} else {
return false
}
}
在checkIfEntryFromToday中调用的函数(可能不相关,但是由于它被称为“我会发布”)
findDayByMils(givenDate){
//takes in the miliseconds and converts to string representing date
const date = new Date(givenDate)
const year = date.getFullYear().toString()
const day = date.getDay().toString()
const month = date.getMonth().toString()
const combinedDate = (day + year + month)
return combinedDate
}