猫鼬的find()函数如何继续执行并等待链中的后续函数首先完成?

时间:2020-05-31 21:41:20

标签: javascript node.js mongoose es6-promise

我正在浏览一些教程资料,我注意到在Mongoose中,我可以某种方式推迟承诺的最终执行,但是我想知道如何完成。

例如,我可以调用find函数,它返回结果的承诺,如下所示:

const blogs = await Blog.find({id : '123'});

猫鼬中的find()函数调用Query对象中的exec()函数以完成查询并返回结果,例如in the line of this file.

然后,假设我对Mongoose Query对象的原型进行了以下修改,以查看是否应该从缓存或Mongo中检索数据:

mongoose.Query.prototype.cache = function() {
   this.useCache = true;
   return this;
}

mongoose.Query.prototype.exec = async function() {
   if (!this.useCache) {    // <-- Apparently, I don't understand how this.useCache can be true if this.cache() was called
      this.exec.apply(this, arguments);
    }
    return 'some cached value';
    return this;
}

// Somehow, the find() section of the chaining is capable of waiting for cache() which is called later to complete to know that useCache is true! But how is that done?
const blogs = await Blog.find({id : '123'}).cache();  // <-- how did this mange to return 'some cached value'?

但是,由于exec()已经在find()函数之前执行的cache()中被调用和求值,因此如何最终仍可以在this.useCache中求值exec() find()最终在解析时起作用?

除非有一些方法可以等待链中所有其他事物完成执行,在这种情况下,cache()等待this.useCache完成执行,否则我希望sudo API_ENDPOINT=`symfony var:export SYMFONY_DEFAULT_ROUTE_URL --dir=..` yarn encore dev 总是是不确定的,不是吗?

我认为这很棒,实际上我想知道如何实现一种类似的链接,这种链接能够以某种方式将最终操作推迟到链的后半部分中的所有功能完成,再解决结果。

注意: 出于可读性的考虑,以上示例是我的实际代码的简化版本。可以在herehere中看到其实际文件的链接。

1 个答案:

答案 0 :(得分:1)

猫鼬中的find()函数调用Query对象中的exec()函数以完成查询并返回结果,例如in the line of this file.

实际上,不是,至少在您的情况下不是。参见the comment from three lines above

// if we don't have a callback, then just return the query object

.exec()仅在传递回调时由find(…, callback)调用。使用诺言时,您不会。

相反,exec方法is called by the then() method of the query使查询成为 thenable ,并在您await查询对象时被使用。