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不是函数
也许蓝鸟不适合猫鼬?
答案 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
函数