为什么将此功能放在承诺中会中断?

我有一个承诺,可以从我的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
  }
tinlud 回答:为什么将此功能放在承诺中会中断?

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

您正在使用匿名函数。匿名函数将this更改为函数的作用域(并且您无法使用this访问外部作用域)。

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

本文链接:https://www.f2er.com/2823234.html

大家都在问