无法在课堂上使用此函数调用

华丽

我有一个叫做的类Scheduler,它使用模块执行cron作业cron我创建了一个函数来获取两个日期之间的天差,如果我在cron作业迭代之外调用它,该函数将起作用,否则它将返回

TypeError:this.getDaysDifference不是一个函数

这是我的代码:

const CronJob = require('cron').CronJob;

class Scheduler {

    async start() {

        // HERE WORKING
        console.log(this.getDaysDifference(new Date('2020-03-29'), new Date('2020-03-30')));

        const job = new CronJob('0 */1 * * * *', async function () {
            let messages = await MessageModel.find();
            for (const msg of messages) {
                // HERE NOT WORKING
                console.log(this.getDaysDifference(new Date(), msg.lastScheduler));
            }
        });

        job.start();
    }

    getDaysDifference = function(start, end) {
        const _MS_PER_DAY = 1000 * 60 * 60 * 24;
        const utc1 = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate());
        const utc2 = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
        return Math.floor((utc2 - utc1) / _MS_PER_DAY);
    }
}

exports.Scheduler = Scheduler;
全堆的家伙

由于您使用this.getDaysDifference所以并未指向回调中的类实例Schedulerfunction

有两种方法可以解决此问题:

  • 使用() => {}非常简单的箭头功能

  • this使用明确将绑定到您的实例functionObj.bind(yourInstance)

您可以使用将结合一个箭头功能this词汇 在回调的定义:

new CronJob('0 */1 * * * *', async () => {
     let messages = await MessageModel.find();
     for (const msg of messages) {
         //this will be the lexical  this i.e. point to the instance o sthe Scheduler class
         console.log(this.getDaysDifference(new Date(), msg.lastScheduler));
        }
});

使用解决方案bind,您可以将的值显式绑定this到类的实例:

let cronJobCallback = async function () {
      let messages = await MessageModel.find();
      for (const msg of messages) {
      // HERE NOT WORKING
      console.log(that.getDaysDifference(new Date(), msg.lastScheduler));
      }
 }
 cronJobCallback = cronJobCallback.bind(this);
 new CronJob('0 */1 * * * *', cronJobCallback);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章