使用bluebird为mongoose,得到“.bind不是函数”

时间:2017-01-07 03:24:56

标签: node.js mongodb bluebird

我将bluebird用于mongoose

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

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

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不是函数

也许蓝鸟不适合猫鼬?

1 个答案:

答案 0 :(得分:4)

你遇到的问题是,mongoose查询不会返回完整的承诺 - 直接引用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函数