为什么我在这里收到错误“不是函数”?

时间:2016-09-02 10:08:56

标签: javascript node.js

我这里有一个nodejs问题,我真的不知道它为什么会发生。

这是我的代码:

	isInTimeSlot() {
		return new Promise((resolve, reject) => {
			var date = new Date()
		    var hour = date.getHours()
		    hour = (hour < 10 ? "0" : "") + hour
		    var min  = date.getMinutes()
		    min = (min < 10 ? "0" : "") + min
		    if (hour >= this.followMinHour && hour <= this.followMaxHour) {
		    	return resolve(42)
		    } else if (hour >= this.unfollowMinHour && hour <= this.unfollowMaxHour) {
		    	return resolve(1337)
		    } else {
		    	return reject()
		    }
		})
	}

	checkProjectTimeSlot() {
		return new Promise((resolve, reject) => {
			var timer = setInterval(function() {
				console.log('Checking if bot is in time slot')
				this.isInTimeSlot()
				.then((mode) => {
					clearInterval(timer)
					resolve(mode)
				})
			}, 5000)		
		})
	}

所以这是我的ES6类的两个简单方法,当我执行它时,我有以下错误:

this.isInTimeSlot()
                     ^
TypeError: this.isInTimeSlot is not a function 

你能看到错误吗?

1 个答案:

答案 0 :(得分:2)

当您处于承诺退回或计时器中时,this会发生变化。

isInTimeSlot() {
    return new Promise((resolve, reject) => {
        var date = new Date()
        var hour = date.getHours()
        hour = (hour < 10 ? "0" : "") + hour
        var min  = date.getMinutes()
        min = (min < 10 ? "0" : "") + min
        if (hour >= this.followMinHour && hour <= this.followMaxHour) {
            return resolve(42)
        } else if (hour >= this.unfollowMinHour && hour <= this.unfollowMaxHour) {
            return resolve(1337)
        } else {
            return reject()
        }
    })
}

checkProjectTimeSlot() {
    var that = this;
    return new Promise((resolve, reject) => {
        var timer = setInterval(function() {
            console.log('Checking if bot is in time slot')
            that.isInTimeSlot()
            .then((mode) => {
                clearInterval(timer)
                resolve(mode)
            })
        }, 5000)        
    })
}