Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!