Thursday 20 April 2017

Losing context of class when invoking method using async.queue

When using async.js's queue function with a class's method as the worker, the class context appears to become lost. The following code gives the value of this as undefined:

const { queue } = require('async');

class ClassName {
  constructor() {
    this.q = queue(this.worker);
  }

  run() {
    this.q.push();
  }

  worker() {
    console.log(this)
  }
}

const x = new ClassName()
x.run()

I can pass the context directly to the worker function as the payload in push. However, I would prefer to be able to refer to the class's context from the method itself. Can anyone help me out with this? I feel like it might just be a lack of understanding of this on my part.



via Tom Hutchinson

No comments:

Post a Comment