Node.js, setTimeout and "this" callback method

I am trying to write a simple polling application using node.js. I want to write an EventEmitter that performs a timer action and emits events based on the result of this periodic action.

I start by creating my own object and inherit from EventEmitter. I start the timer using setInterval and set the method to call after the timer expires. In the timer callback method, I want to reference the variable of the object I created, but this does not seem to refer to the object.

How can I refer to my variable in this method? Here is my code:

 var util = require('util'), events = require('events'), timers = require('timers'), redis = require('redis'); // define worker object var JobPoller = function () { // inherit event emitter events.EventEmitter.call(this); // save reference to database this.db = redis.createClient(); // start main loop this.interval_id = timers.setTimeout(this.check, 1000); }; JobPoller.prototype.check = function () { // pop a job off the queue if possible this.db.rpop('pdf-job-queue', function (err, result) { if (err != null) this.emit('error', err); if (result != null) this.emit('job', JSON.parse(result)); // check for more jobs this.interval_id = timers.setTimeout(this.check, 1000); }); }; // inhert from event emitter util.inherits(JobPoller, events.EventEmitter); // export the poller instance module.exports = new JobPoller; 
+6
source share
1 answer

this.check is just a simple function, the value of this inside this function will be determined when the function is called.

Node must support bind so that you can bind a function to your desired this as follows:

 this.interval_id = timers.setTimeout(this.check.bind(this), 1000); 

Alternatively, you can use closure to manually force this to use, so you want:

 var self = this; this.interval_id = timers.setTimeout(function() { self.check() }, 1000); 
+14
source

Source: https://habr.com/ru/post/909794/


All Articles