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

How does mongoose's find() function hold on to its execution and wait for a later function in its chain to complete first?

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

例如,我可以调用 find 函数,它 return 结果的承诺如下:

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

mongoose中的find()函数调用Query对象中的exec()函数完成查询并return得到结果,如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() 已经在链中 cache() 函数之前执行的 find() 中被调用和求值,所以 this.useCache 怎么可能仍然被求值在 exec() 函数中终于解决了?

除非有一些方法可以等到链中的其他所有内容都完成执行,在这种情况下 find() 等待 cache() 完成执行,我本以为 this.useCache总是未定义,不是吗?

我觉得这很神奇,实际上我想知道如何实现一种类似的链接,它能够以某种方式推迟最终操作,直到链后面部分的所有函数都完成,然后再解析结果.

注: 为了便于阅读,上面的示例是我对实际代码的简化版本。可以看到指向其实际文件的链接 here and here.

The find() function in mongoose calls the exec() function in the Query object to complete the query and return the result, like 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 使查询 然后可用 ,并在您 await 查询对象时使用。