Search code examples
node.jsforeachmongoosegeneratorkoa

forEach using generators in Node.js


I'm using Koa.js framework and Mongoose.js module.

Normally to get a result from MongoDB I code like this:

var res = yield db.collection.findOne({id: 'my-id-here'}).exec();

But I need to execute this line for every element of an array named 'items'.

items.forEach(function(item) {
  var res = yield db.collection.findOne({id: item.id}).exec();
  console.log(res)  // undefined
});

But this code doesn't run as yield is in the function. If I write this:

items.forEach(function *(item) {
  var res = yield db.collection.findOne({id: item.id}).exec();
  console.log(res)  // undefined
});

I'm not getting the result in res variable either. I tried to use 'generator-foreach' module but that didn't worked like this.

I know that this is my lack of knowledge about the language literacy of Node.js. But can you guys help me finding a way how to do this?


Solution

  • Thanks guys, I've done this using the 'CO' module. Thanks.

    var co = require('co');
    
    items.forEach(co(function* (item) {
      var img = yield db.collection.findOne({id: item.id}).exec();
    }));
    

    EDIT: With the latest version of CO, you need co.wrap() for this to work.