Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it necessary to have 'yield' in this statement from node app?

Tags:

node.js

koa

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;
});
like image 333
user482594 Avatar asked Nov 23 '25 07:11

user482594


1 Answers

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.

like image 100
James Moore Avatar answered Nov 25 '25 21:11

James Moore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!