0

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?

alramdein
  • 810
  • 2
  • 12
  • 26
  • 1
    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)) } – Ebay Nov 01 '21 at 12:45
  • but what do you mean by `context` in `the context of the callback that you call is not the same`? – alramdein Nov 01 '21 at 12:48
  • Does this answer your question? [What is the use of the JavaScript 'bind' method?](https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method) – xdeepakv Nov 01 '21 at 12:49
  • @alramdein you may want to post that as an answer. – Lajos Arpad Nov 01 '21 at 12:49

1 Answers1

0

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.

Ebay
  • 355
  • 2
  • 12