Mongoose promises documentation says queries are not promises?

后端 未结 3 565
庸人自扰
庸人自扰 2020-12-10 19:11

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

Mongoose async operations, like .save() and queries, return thenables. This

相关标签:
3条回答
  • 2020-12-10 19:33

    All promises are thenables, but not all thenables are promises. To make things more complicated, not all promises are Promises (instances created by JavaScript's built-in Promise constructor).

    JavaScript promises are an implementation of the Promises/A+ specification, which defines the terms like this:

    1.1 “promise” is an object or function with a then method whose behavior conforms to this specification.

    1.2 “thenable” is an object or function that defines a then method.

    So Mongoose's queries are not promises, not even by that definition, since their then method is not compatible with the Promises/A+ spec. See JohnnyHK's answer for why they aren't compatible with the Promises/A+ spec (they run the query).

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

    They only act a bit like promises. They are not promises. Their then is not implemented per the spec, it has side effects (running the query). If you want a true promise, see JohnnyHK's answer (e.g., use exec).


    In general, if you have a thenable that's at least somewhat promise-like, you can get a proper promise for it by using Promise.resolve:

    Promise.resolve(theThenable)
    .then(/*...*/)
    .catch(/*...*/)
    .finally(/*...*/);
    

    Promise.resolve will provide a true Promise instance that is slaved to the Mongoose thenable/promise. That would work on a Mongoose query (provided you only do it once; exec is the better way with Mongoose queries).

    0 讨论(0)
  • 2020-12-10 19:36

    From the documentation:

    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.

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

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

    let promise = Test.findOne({}).exec();
    
    0 讨论(0)
  • 2020-12-10 19:44

    They are "promise like", which means you can await them and call .then() and .catch() on them, however they are not instanceof Promise.

    0 讨论(0)
提交回复
热议问题