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

181
Vistas
How can I run watch changes in asynchronous way NodeJS Mongoose

For the past 2 days I have been struggling on this thing. I want to watch for changes on particular collection. All of the logic for these changes is in asynchronous way. I tried to make the EventEmitter callback function to be asynchronous but still works in synchronous manner.

Pseudo code example:

const someLogicFunction1 = async () => {
   // some logic here
}

const someLogicFunction2 = async () => {
   // some logic here
}

const collectionEventEmitter = Collection.watch();

collectionEventEmitter.on('change', async (change) => {
  await someLogicFunction1();
  await someLogicFunction2(); // has to wait for first function to finish
});

As I explained above I tried this approach but still runs synchronously. The second function usually has to wait for the first function to finish its task in order for the whole code to be properly working.

EDIT: From what I have found it seems that the callback function firstly gets all this "change" parameter event objects and then executes the code. What I need actually is to execute the code for every "change" event parameter - not for all of them at once.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

One solution is to make someLogicFunction1() returning a promise and calling someLogicFunction2(); in then of first function, like this:

await someLogicFunction1()
  .then(function(){
    someLogicFunction2();
});

You just need to modify someLogicFunction1(); like this:

someLogicFunction1( )
{
  return new Promise( async function( resolve, reject ) {
    // Do your stuff here
  }); // eo promise
} 

Don't forget to resolve() in someLogicFunction1 function.

resolve();

You can also reject() in someLogicFunction1 and catch the error when you call this function.

reject();

You can pass an argument to resolve and reject and get it in your call.

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