Search code examples
javascriptnode.jscallbacklistenerworker-thread

Undefined object properties inside callback function in Worker Thread's parentPort listener


I have a worker object something like this:

const WorkerObject = {
  mapProp: new Map(),

  funA() {
    // some task
  },

  funB() {
    // some task
  },

  workerListener() {
    parentPort.on('message', async (message) => {
      console.log(this.mapProp) // returning Map(0) {}
    })
  }
}

When I call mapProp property in parentPort() listener callback inside the workListener() function, it is referencing the Map that I have assigned at the top of the object. This is just what I expected.

But I need to reduce the Cognitive Complexity so I move the call back function to another defined function inside the WorkerObject.

const WorkerObject = {
  mapProp: new Map(),

  funA() {
    // some task
  },

  funB() {
    // some task
  },

  async doBulkIndex(message) {
    console.log(this.mapProp) // returning undefined
  },
  
  workerListener() {
    parentPort.on('message', this.doBulkIndex)
  }
}

But somehow, now the Map always returning undefined. Basically, all properties that I tried to access inside doBulkIndex() are undefined. Why is it like that? And how to make my second approach has the same behavior as the previous one?


Solution

  • the context of the callback that you call is not the same, I think you should bind "this" to it,

     workerListener() { parentPort.on('message', this.doBulkIndex.bind(this))}
    

    at the first one, this keyword refers to WorkerObject But in the second one, this refers to "doBulkIndex" context. you can search about context and bind.

    see: bind keyword

    so we manually change the context to main object using bind.