在传递的回调完成后,是否会发出Mongoose查询`then`调用?

时间:2017-01-19 22:34:15

标签: node.js mongoose promise es6-promise

我意识到Mongoose中promises的标准做法是使用exec(),但是下面的工作(或至少看起来)并且我想了解流程。我并不反对使用exec,我只是在探索这一点。

在以下Mongoose操作中:

let id:string;

SomeDocument.remove({}, (err) => { //clears collection
  someDoc = new SomeDocument(data); //creates a new doc for the collection. Id is created here from what I understand.
  someDoc.save( (err, result) => { doSomething(); });//doSomething gets called sometime in the future.
  id = someDoc._id.toString();
}).then( (result) => {doSomethingElse(id)});//This works - but will doSomethingElse always be called after the first annonymous callback completes?

我知道doSomething()将在未来的某个时刻被调用 - 没问题。问题是,在调用doSomethingElse调用中then之前,移除调用的第一个回调是否完成。似乎是id正确地填充了doSomethingElse,但我想确保这不仅仅是时间上的侥幸 - 也就是说我想知道我是否可以依赖于回调在then之前完成。我正在使用标准的ES6承诺(NodeJS.Global.Promise)。

另一种方法是,在删除操作完成后调用then,但在回调完成之前调用(似乎不是 - 但我想确认)。

如果我不正确地解释这一点,请让我直截了当。

1 个答案:

答案 0 :(得分:1)

是的,正如@JaromandaX在评论中解释的那样,回调的顺序是确定性的。

然而,它仍然是错误的代码,你不应该依赖这种行为。如果您使用的是promises,请不要将回调传递给remove;只将回调传递给then

SomeDocument.remove({})
.then(() => {
  const someDoc = new SomeDocument(data);
  someDoc.save().then(doSomething); // doSomething will get called in the future.
  return someDoc._id.toString();
//^^^^^^
})
.then(doSomethingElse); // doSomethingElse will get passed the id
将使用上一个回调的结果调用

doSomethingElse保证已完成此回调。