0

I would like to do something like this.

function* iterateRecord() {

    const db = yield MongoClient.connect('');

    const collection = db.collection('');

    const query = {}


    const cursor = collection.find(query);

    while (yield cursor.hasNext()) {

        const bsonObject = yield cursor.next();
    }
}

for(record of iterateRecord())
{
    //do stuff
}

Now as you can see this will not work the db yield will be the first iteration of the for. So what I would like to do is only return the yield at the cursor.next.

Is this possible? I have tried a few things but i always get to the multiple yield that not part of the iteration.

thanks

Pintac
  • 1,565
  • 3
  • 21
  • 38
  • please have a look, what [`yield`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield) is doing. it pauses the function and returns the value. – Nina Scholz Nov 08 '16 at 12:41
  • Yes I understand what yield is doing. The reason i have the yield in db and in hasNext is because i don't want to have to deal with promises or callbacks. – Pintac Nov 08 '16 at 12:44
  • 2
    You might want to have a look at [this answer](http://stackoverflow.com/a/29281361/1048572) – Bergi Nov 08 '16 at 13:48
  • hmmm nope :-). I have a case where the 'answer' will work but not this instance and its all 'yield cursor.hasNext' fault. – Pintac Nov 08 '16 at 14:02

1 Answers1

0

You're mixing two different things here: (1) js generators and (2) usage of js generators to emulate async/await.

There are a number of libraries for (2) like co or bluebird, but all of them expect that you're going to yield promises.

It will not work with for loop for sure because it doesn't wait promises to resolve and doesn't return the result back to generator.

teq
  • 1,494
  • 1
  • 11
  • 12