Mongoose 承诺文档说查询不是承诺? [英] Mongoose promises documentation says queries are not promises?

查看:22
本文介绍了Mongoose 承诺文档说查询不是承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自文档(Mongoose v5.4.1,最新版本):

From the docs (Mongoose v5.4.1, latest version):

Mongoose 异步操作,如 .save() 和查询,返回可用的.这意味着您可以执行 MyModel.findOne({}).then()

Mongoose async operations, like .save() and queries, return thenables. This means that you can do things like MyModel.findOne({}).then()

文档中的第二段说明:

Mongoose 查询不是承诺.他们有一个 .then() 函数用于 co和 async/await 为方便起见.

Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience.

什么 Javascript MDN 网页声明:

then() 方法返回一个 Promise.

The then() method returns a Promise.

这是否意味着 mongoose 有另一种异步函数的实现,它们为异步操作的结果保留了 then 关键字?

Does this mean that mongoose has another kind of implementation for async functions where they reserved the then keyword for the result of the async action?

换句话说,它们的行为就像承诺,但不是 JS 承诺?

In other words, they act like promises but are not JS promises?

推荐答案

来自 文档:

Mongoose 查询不是承诺.他们有一个 .then() 函数用于 co和 async/await 为方便起见.然而,与 promises 不同的是,调用一个查询的 .then() 可以多次执行查询.

Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience. However, unlike promises, calling a query's .then() can execute the query multiple times.

因此与实际的承诺不同,如果您对查询多次调用 then(),您实际上会多次执行查询(或更新).

So unlike an actual promise, if you call then() multiple times on the query, you actually execute the query (or update) multiple times.

如果你想要一个实际的承诺,调用 exec() 在查询中.

If you want an actual promise, call exec() on the query.

let promise = Test.findOne({}).exec();

这篇关于Mongoose 承诺文档说查询不是承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆