Kiw*_*Lau 1 mongodb node.js bluebird
const Promise = require("bluebird");
const mongoose = require("mongoose");
mongoose.Promise = Promise;
Run Code Online (Sandbox Code Playgroud)
我想使用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()
Run Code Online (Sandbox Code Playgroud)
但是我得到了错误:getAutherOfBook(...)。bind不是一个函数
也许蓝鸟不适合猫鼬吗?
您遇到的问题是猫鼬查询不会返回完整的保证承诺-直接引用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'));
Run Code Online (Sandbox Code Playgroud)
换句话说,该then函数是语法糖而不是a promise,这就是为什么bindand和其他promise函数不起作用的原因。
要使其工作,您可以将其包装成完整的承诺,也可以使用exec文档中建议的功能
| 归档时间: |
|
| 查看次数: |
386 次 |
| 最近记录: |