我正在使用Koa.js框架和Mongoose.js模块。
通常要从 MongoDB 获得结果,我的代码如下:
var res = yield db.collection.findOne({id: 'my-id-here'}).exec();
但我需要为名为“items”的数组的每个元素执行这一行。
items.forEach(function(item) {
var res = yield db.collection.findOne({id: item.id}).exec();
console.log(res) // undefined
});
但是此代码不会运行,因为 yield 在函数中。如果我写这个:
items.forEach(function *(item) {
var res = yield db.collection.findOne({id: item.id}).exec();
console.log(res) // undefined
});
我也没有得到 res 变量的结果。我尝试使用“ generator-foreach ”模块,但它并没有像这样工作。
我知道这是我对 Node.js 的语言素养缺乏了解。但是你们能帮我找到一种方法吗?