我正在尝试传递依赖项中注入的服务。该函数的第一个调用起作用。但是,当我在另一个嵌套函数中调用注入函数时,会出现错误。
控制器代码:
CronScheduleController类{
constructor(log, calculationService) {
this.log = log;
this.calculationService = calculationService;
}
async weeklyCronJob() {
this.log.info('Weekly CRON Job is running');
var rule = new schedule.RecurrenceRule();
var job = schedule.scheduleJob(rule, function () {
this.log.info('Weekly CRON Job Started');
});
}
}
我收到第一条日志消息=>'每周CRON作业正在运行'
但是第二条日志消息抛出错误=>'每周CRON作业已开始'
错误是:
/controllers/cronSchdule.js:28 logger.info('每周CRON作业已开始'); ^
TypeError:logger.info不是函数
任何人都可以帮助解决此问题。/
谢谢。
答案 0 :(得分:0)
当您在函数this
内时,关键字不代表该类,但是该函数的词法范围尝试使用箭头函数(假定您使用async
await
,因此假定为ES6)< / p>
constructor(log, calculationService) {
this.log = log;
this.calculationService = calculationService;
}
async weeklyCronJob() {
this.log.info('Weekly CRON Job is running');
var rule = new schedule.RecurrenceRule();
var job = schedule.scheduleJob(rule, () => {
this.log.info('Weekly CRON Job Started');
});
}
如果未创建参考对象,则使用参考访问类,
constructor(log, calculationService) {
this.log = log;
this.calculationService = calculationService;
}
async weeklyCronJob() {
this.log.info('Weekly CRON Job is running');
var rule = new schedule.RecurrenceRule();
var that = this; // <== HERE
var job = schedule.scheduleJob(rule, function() {
that.log.info('Weekly CRON Job Started'); // <== HERE
});
}