为什么将此函数放在promise中会中断?

问题描述 投票:0回答:1

我保证会从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
  }

我保证会从Firebase实时数据库检索条目,并使用回调检查特定条目是否在今天的日期进行。回调函数(在不运行时起作用...

javascript reactjs this es6-promise
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.