Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 猫鼬';s find()函数保持其执行,并等待其链中的后续函数首先完成?_Javascript_Node.js_Mongoose_Es6 Promise - Fatal编程技术网

Javascript 猫鼬';s find()函数保持其执行,并等待其链中的后续函数首先完成?

Javascript 猫鼬';s find()函数保持其执行,并等待其链中的后续函数首先完成?,javascript,node.js,mongoose,es6-promise,Javascript,Node.js,Mongoose,Es6 Promise,我正在阅读一些教程材料,我注意到在Mongoose中,我可以以某种方式推迟其中承诺的最终执行,但我想知道如何做到这一点 例如,我可以调用find函数,它返回结果的承诺,如下所示: const blogs = await Blog.find({id : '123'}); mongoose中的find()函数调用查询对象中的exec()函数来完成查询并返回结果,如 然后,假设我对Mongoose查询对象的原型进行了以下修改,以确定我应该从缓存还是从Mongo检索数据: mongoose.Query

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

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

const blogs = await Blog.find({id : '123'});
mongoose中的
find()
函数调用查询对象中的
exec()
函数来完成查询并返回结果,如

然后,假设我对Mongoose查询对象的原型进行了以下修改,以确定我应该从缓存还是从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'?
mongoose.Query.prototype.cache=function(){
this.useCache=true;
归还这个;
}
mongoose.Query.prototype.exec=异步函数(){
如果(!this.useCache){//
mongoose中的
find()
函数调用查询对象中的
exec()
函数来完成查询并返回结果,如

实际上没有,至少在你的情况下没有。参见:

如果传递回调,则
.exec()
方法仅由
find(…,callback)
调用。使用承诺时,不会调用


取而代之的是
exec
方法,该方法使查询能够进行,并且在
等待查询对象时使用该方法。

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