将蓝鸟用于猫鼬,得到“.bind 不是函数”

Use bluebird for mongoose, got ".bind is not a function"

我用bluebird for mongoose:

const Promise = require("bluebird");
const mongoose = require("mongoose");
mongoose.Promise = Promise;

我想使用 Promise.bind 在承诺链中共享变量:

function getAutherOfBook(name)
{
    return Book.findOne(
        {
            name: name
        }, "-_id auther")
        .then(doc =>
        {
            return doc.auther;
        });
};


function geNationalityOfAuther(name)
{
    return Auther.findOne(
        {
            name: name
        }, "-_id nationality")
        .then(doc =>
        {
            return doc.nationality;
        });
};


getAutherOfBook("The Kite Runner")
    .bind({})
    .then(auther =>
    {
        this.auther = auther;
        return geNationalityOfAuther(auther);
    })
    .then(nationality =>
    {
        console.log("auther: ", this.auther);
        console.log("nationality: ", nationality);
    })
    .bind()

但我收到错误消息:getAutherOfBook(...).bind 不是函数

也许蓝鸟不适用于猫鼬?

您遇到的问题是 mongoose 查询没有 return 完整的承诺——直接引用 http://mongoosejs.com/docs/promises.html (v4.7.6)

// A query is not a fully-fledged promise, but it does have a `.then()`.
query.then(function (doc) {
  // use doc
});

// `.exec()` gives you a fully-fledged promise
var promise = query.exec();
assert.ok(promise instanceof require('mpromise'));

换句话说,then 函数是语法糖而不是 promise,这就是 bind 和其他 promise 函数不起作用的原因。

要使其正常工作,您要么将其包装在一个完整的承诺中,要么使用文档中建议的 exec 函数