gpt4 book ai didi

node.js - 将 Bluebird 用于 Mongoose ,得到 ".bind is not a function"

转载 作者:行者123 更新时间:2023-12-02 08:16:35 25 4
gpt4 key购买 nike

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

也许 Bluebird 不适用于 Mongoose ?

最佳答案

您遇到的问题是 mongoose 查询不会返回完整的 promise ——直接引用 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 函数不起作用的原因.

要使其工作,您要么将其包装在一个完整的 promise 中,要么按照文档中的建议使用 exec 函数

关于node.js - 将 Bluebird 用于 Mongoose ,得到 ".bind is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41517477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com