【问题标题】:Mongoose async promise don't seem to work猫鼬异步承诺似乎不起作用
【发布时间】:2021-02-19 09:39:39
【问题描述】:

我在 mongoose 中使用 async' 有点麻烦。基本上我的代码如下:

function() {
   SchemaOne.findById(fooIdOne).exec().then( x => {
      // Some first instructions
      myCollection.foreach( y => {
         SchemaTwo.findById(fooIdTwo).exec().then( z => {
            // Some second instructions
         });
      });
   }).then(() => {
      // Code to execute after
   });
}

在这里,我希望在“要执行的代码”之前制作“第一条指令”和“第二条指令”,但最后一个“然后”似乎并没有等待第二条指令的制作。

需要一点帮助! 非常感谢 !凯夫'。

【问题讨论】:

  • 你永远不会返回这个承诺,所以最后一个 then 将在第一个 then 之后立即执行
  • 所以在这里我应该找到一种方法将“SchemaTwo.findById”与“SchemaOne.findById”置于同一级别以解决此问题?因为我需要在 foreach 中进行第二个查询,这使它变得更加复杂

标签: javascript mongodb mongoose mongoose-schema


【解决方案1】:

您的forEach 调用是同步执行的,您不会在then 回调中返回承诺。

您应该收集在循环中创建的 Promise,并返回其中的 Promise.all

function() {
   SchemaOne.findById(fooIdOne).exec().then( x => {
      // Some first instructions
      let promises = [];
      myCollection.foreach( y => {
         promises.push(SchemaTwo.findById(fooIdTwo).exec().then( z => {
            // Some second instructions
         }));
      });
      return Promise.all(promises);
   }).then(() => {
      // Code to execute after
   });
}

【讨论】:

  • 好的,我看到了异步问题,但找不到修复它的代码,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 2015-05-12
  • 2018-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多