我想将koa与mongodb和mongoose一起使用,代码如下:
var getMessage = function*(params) {
var messages = MessageModel.find({
to: params.to
}, function(err, m) {
if (err) return console.error(err);
// How to get the data out of here to work with them?
console.log(m);
});
yield messages.fields;
}
app.get('/message/to/:to', function*(next) {
this.body =
yield getMessage(this.params);
});
功能本身有效。这意味着,数据打印在控制台上,但我不知道如何从函数中获取数据,以便使用它们。最好的方法是什么?
答案 0 :(得分:4)
您将使用.find().exec()
返回的承诺而不使用生成器:
var getMessage = function (params) {
return MessageModel.find({
to: params.to
}).exec();
}
app.get('/message/to/:to', function*(next) {
this.body = yield getMessage(this.params);
});
或在生成器中产生promise并返回所需的值:
var getMessage = function*(params) {
var data = yield MessageModel.find({
to: params.to
}).exec();
return data;
}
请查看http://blog.stevensanderson.com/2013/12/21/experiments-with-koa-and-javascript-generators/,了解有关可以收益的更多信息。
答案 1 :(得分:2)
你有没有尝试过这个承诺呢? https://github.com/LearnBoost/mongoose/issues/1859
var getMessage = function*(params) {
var mPromise = MessageModel.find({
to: params.to
}).exec();
yield mPromise;
}
app.get('/message/to/:to', function*(next) {
this.body =
yield getMessage(this.params);
});