javascript - 为什么将这个函数放在 Promise 中时会中断?
问题描述
我有一个承诺,会从我的 Firebase 实时数据库中检索条目,并使用回调检查特定条目是否是在今天的日期创建的。当我将回调函数(不在承诺中时有效)移动到承诺中时,会导致以下错误:
TypeError:无法读取 null 的属性“checkIfEntryFromToday”
我尝试将 .this 绑定到构造函数中的函数,但这没有帮助。
这是代码:
调用 promise 的主函数
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
}
解决方案
这是问题所在:ref.on("value", function(snapshot){
您正在使用匿名函数。匿名函数更改this
为在函数范围内(您无法使用 访问外部范围this
)。
要解决此问题,请将该行更改为:ref.on("value", snapshot => {
推荐阅读
- javascript - 如何从数据记录器中制作及时更新的图表?
- c# - 带有 DataModel 和 Entity 的 WebApi Lambda
- excel - 根据另一个电子表格中的选定数据显示电子表格中的数据
- bash - bash 脚本接受 cp 文件 >> .bak 或 .190318 选项的命令行参数(文件)和选项(扩展名)
- java - 缩放画布绘图以适应活动中的自定义视图
- powershell - 在PowerShell中使用目录Test-Path vs System.IO.File
- java - 可在 for 循环内运行
- javascript - React Router 的 ES6 导入错误
- javascript - 反应:更改悬停时显示的文本
- ruby - Ruby - 按值将哈希排序为降序