Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda