将bluebird用于猫鼬,得到".bind不是函数". [英] Use bluebird for mongoose, got ".bind is not a function"

查看:87
本文介绍了将bluebird用于猫鼬,得到".bind不是函数".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 bluebird 用于

我想使用 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不是一个函数

But I got the error: getAutherOfBook(...).bind is not a function

也许蓝鸟不适用于猫鼬?

Maybe bluebird is not working for mongoose?

推荐答案

您遇到的问题是猫鼬查询不会返回完整的承诺-直接引用

The problem you are having is that mongoose queries does not return full fledge promises -- directly quoting 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函数不起作用的原因.

In other words, the then function is syntax sugar and not a promise which is why the bind and other promise functions does not work.

要使其正常工作,您可以将其包装成完整的承诺,也可以按照文档中的建议使用exec函数

To make it work, you either wrap it up in a full promise or use the exec function as suggested in the docs

这篇关于将bluebird用于猫鼬,得到".bind不是函数".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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