首页 > 解决方案 > 为什么将这个函数放在 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
  }

标签: javascriptreactjsthises6-promise

解决方案


这是问题所在:ref.on("value", function(snapshot){

您正在使用匿名函数。匿名函数更改this为在函数范围内(您无法使用 访问外部范围this)。

要解决此问题,请将该行更改为:ref.on("value", snapshot => {


推荐阅读