yourfavorite yourfavorite - 4 years ago 75
Javascript Question

Setting properties of parent class in child module nodejs

I believe there is probably a structure issue that could solve this problem, but I'm unsure of how to keep set values for a parent class that calls a method within a module. I have tried to simplify my code as much as possible.

I have a series of tasks that I keep track of in a class and run on an interval. Each task fetches data from a remote database and then processes it. While in this example I am only needing to set task.fetching. There are a couple of other values I'd like to be able to update from within the runner.js file.

I should note that if possible, I'm interested in how to solve this problem as a concept and not specifically in finding some module that can handle running tasks for me.

// task.js
const runner = require('./runner');

class Task {
constructor(params) {
this.details = params.details;
this.fetching = false;
this.interval = null;
}

start() {
this.interval = setInterval(() => {
if (!this.fetching) {
runner.run(this.details);
}
}, this.details.frequency * 1000);
}
}

module.exports = Task;


// runner.js
const run = (task) => {
fetch(task.url)
.then(parseData)
.then(data => {
if (task.format === 'type') {
return formatItems(data.items);
}

return {};
})
.then(items => {
if (Object.keys(items).length > 0) {
console.log(`Found ${Object.keys(items.newItems).length} new items and ${Object.keys(items.updatedItems).length} updated items`);
}

// *** NEED TO SET TASK FETCHING TO FALSE HERE
})
.catch(e => {
console.log('ERROR:', e);
});
};

Answer Source

task.fetching = false... not sure I get the question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download