简体   繁体   中英

Why is this function breaking when it is placed inside of a promise?

I have a promise that retrieves entries from my Firebase Realtime Database, and using a callback, checks if the specific entries were made on today's date. The callback function (which works when not in the promise) results in the following error when I move it inside of the promise:

TypeError: Cannot read property 'checkIfEntryFromToday' of null

I have tried binding .this to the function in my constructor, but that does not help.

Here is the code:

Main function that calls the 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);
      });
    })
  }

function checkIfEntryFromToday that creates the error

checkIfEntryFromToday(milsToEvaluate){
    const dayOfEntry = this.findDayByMils(milsToEvaluate)
    const today = this.findDayByMils(new Date())
    if (dayOfEntry === today) {
      return true
    } else {
      return false
    }
  }

function called in checkIfEntryFromToday (maybe irrelevant, but since it's called I'll post it)

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
  }

Here is the problem: ref.on("value", function(snapshot){

You are using an anonymous function. Anonymous functions change this to be in the scope of the function (and you can't access the outside scope using this ).

To get around the issue, change that line to: ref.on("value", snapshot => {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM