Reputation: 12523
I am introduce myself in JavaScript and Nodejs.
I have created a class with a constructor.
Inside this constructor a cron job is executed every minute.
The cronjob deletes entries from a Map that is defined as a class field.
class Infos{
static TEN_SECS = 10000;
static cron = require('node-cron');
static codeMap = new Map();
static evictionRegisty = new Map();
constructor() {
console.log('Create repo!');
//Run each minute
cron.schedule('* * * * *', function() {
console.log('Scheduler executed!');
this.evictionRegisty.forEach((key, value, map) => {
if (key > Date.now() - TEN_SECS){
this.codeMap.delete(value);
this.evictionRegisty.delete(key);
console.log('Remove k/v =' + key + '/'+ value)
}
});
});
};
the cronjob works fine and will be executed every minute. For any reason there is an exception when I call the foreach method of the evictionRegisty Map:
TypeError: Cannot read property 'forEach' of undefined
as a Java Developer I would say there is no Map in this scope of the schedule function. But if that is the case, how can I access the map?
Thanks for your help
Upvotes: 1
Views: 3792
Reputation: 521
This error mean the 'this' object has no 'evictionRegisty' field. This means it's not the 'Infos' class. To solve this, you need to pass the variables as inputs to callback function or simply loose the 'this' before calling the 'evictionRegisty'. Your loop would be:
evictionRegisty.forEach((key, value, map) => {
if (key > Date.now() - TEN_SECS){
this.codeMap.delete(value);
this.evictionRegisty.delete(key);
console.log('Remove k/v =' + key + '/'+ value)
}
}
Upvotes: 0
Reputation: 714
You are right, you cannot access the variable within the function because it is out of scope.
Set a variable equal to the scope outside of the function, and use that while you're within your function, like so:
class Infos{
static TEN_SECS = 10000;
static cron = require('node-cron');
static codeMap = new Map();
static evictionRegisty = new Map();
var root = this;
constructor() {
console.log('Create repo!');
//Run each minute
cron.schedule('* * * * *', function() {
console.log('Scheduler executed!');
root.evictionRegisty.forEach((key, value, map) => {
if (key > Date.now() - TEN_SECS){
this.codeMap.delete(value);
this.evictionRegisty.delete(key);
console.log('Remove k/v =' + key + '/'+ value)
}
});
});
};
Upvotes: 2