While I was trying to use 'koa-router' module for koa, I saw the example code snippet below.
app.get('/users/:id', function *(next) {
var user = yield User.findOne(this.params.id);
this.body = user;
});
My question is, why does it have yield right before it gets user info? Why can't code be something like below without yield? Is there major difference?
app.get('/users/:id', function *(next) {
var user = User.findOne(this.params.id);
this.body = user;
});
The function with the asterisk function *(){} is a generator function, which allows pausing and resuming flow within the function by using the yield keyword.
A generator function without a yield is useless, they go hand in hand.
Behind the scenes in koa your generator function is being called by the co library which handles all the asynchronous operations, abstracting the callback / promise into the library, leaving you with a flatter simpler code.
I created a screencast on understanding generators that you might find helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With