使用蓝鸟mongoose,得到“.bind不是一个函数”
我使用蓝鸟的mongoose :
const Promise = require("bluebird"); const mongoose = require("mongoose"); mongoose.Promise = Promise;
我想使用Promise.bind在promise链中共享variables:
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?
你遇到的问题是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函数不起作用的原因。
为了使其工作,您可以将其包装在一个完整的承诺中,或使用文档中build议的exec
函数