Mongoose promises documentation says queries are not promises?

后端 未结 3 585
庸人自扰
庸人自扰 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).

提交回复
热议问题