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

224
Vistas
How to retrieve value from process.on in nodejs?

The current code that I am using:

   async function MainFunction(){
        let arrOO;
        process.on('message', (jData) => {
            let sName;
            if(jData.koota){
                sName = jData.koota[0]
            }

            console.log(sName + ' hello!')
            arrOO = sName
        })
        
        console.log(arrOO + ' calling outside of .on')
   }

I am attempting to print jData.koota[0] which is assigned to sName so that it can used in the whole function. In this case, outside of the process.on, I want to print it. When this code is run, 'undefined' is returned at console.log(arrOO + ' calling outside of .on'). How would I call sName outside of process.on?

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

process.on() just installs an event listener and immediately returns, so your console.log() runs BEFORE any events have happened. process.on() is referred to as non-blocking. That means it does some initial work and then immediately returns and the actual data arrives sometime later when it calls your callback.

So, your console.log() is just attempting to look at the data before any data has been put in there. Note that most of the time when you're trying to assign to a higher scoped variable from an asynchronous callback function, that's a likely sign of a coding error because code at the higher scope won't have any idea when to access that data.

For any code that wants to know about those process messages, you need to either put that code inside the process.on() callback or put it in a function that you call from inside that callback. That's the ONLY way you will know when an incoming message has occurredl and when some data is available.

Here's one option:

function MainFunction(){
    process.on('message', (jData) => {
        let sName;
        if(jData.koota){
            sName = jData.koota[0];
            // call some function and pass it the new data
            newDataArrived(sName)
        }
    });        
}

// this function gets called when we have a new sName 
function newDataArrived(sName) {
   // put code here that uses the data
   console.log(sName);
}

Or, you can make it a promise based interface that resolves a promise on the next matching event you get:

function MainFunction() {
     return new Promise(resolve => {
         function messageHandler(jData) {
             if (jData.koota) {
                  resolve(jData.koota);
                  // remove message listener so they don't pile up
                  // since a promise is a one-shot device, we can
                  // only use this promise once
                  process.off('message', messageHandler);
             }
         }
         process.on('message', messageHandler);             
     });
}

Mainfunction().then(sName => {
   // use sName here
});
about 4 years ago · Santiago Gelvez 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