我如何 运行 以异步方式观察 NodeJS Mongoose 的变化

How can I run watch changes in asynchronous way NodeJS Mongoose

在过去的两天里,我一直在为这件事苦苦挣扎。我想关注特定系列的变化。这些更改的所有逻辑都是异步方式。我尝试将 EventEmitter 回调函数设为异步,但仍以同步方式工作。

伪代码示例:

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
});

正如我上面所解释的,我尝试了这种方法,但仍然同步运行。第二个函数通常必须等待第一个函数完成其任务才能使整个代码正常工作。

编辑: 从我发现的情况来看,回调函数似乎首先获取所有这些“更改”参数事件对象,然后执行代码。我实际上需要的是为每个“更改”事件参数执行代码——而不是一次为所有这些参数执行代码。

一个解决方案是让 someLogicFunction1() 返回一个承诺并在第一个函数的 then 中调用 someLogicFunction2();,如下所示:

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

你只需要像这样修改someLogicFunction1();

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

不要忘记在 someLogicFunction1 函数中 resolve()

resolve();

你也可以在 someLogicFunction1reject() 并在调用此函数时捕获错误。

reject();

您可以传递一个参数来解决和拒绝并在您的调用中获取它。