Reputation: 3026
I'm trying to figure out the use of yield in koa routing.
as an example,
router.get('/data', function *(next) {
this.body = yield someData;
});
If I wanted to send a static file, I could use koa-send like so :-
router.get('/data', function *(next) {
yield send(this, 'file.html');
});
However if i assign the 2nd yield to this.body, it doesnt work.
so what does
this.body = yield ...
actually mean and why don't I need to assign the 2nd yield to the body?
Upvotes: 1
Views: 965
Reputation: 1901
If you peek inside the koa-send library you'll notice this:
ctx.body = fs.createReadStream(path);
Basically the library is assigning a stream to this.body
, then when you were trying to assign what is returned by calling yield send(this, 'file.html')
, which appears to be the file path and name, you're breaking / overwriting what the library was trying to do.
Now if you'd like, you could choose to not use koa-send
and instead just do this:
this.body = fs.createReadStream('file.html');
Getting to your specific question
this.body = yield ...
You call yield (inside generators) on Promise/thunk/generator returning functions that do something asynchronous, which pauses execution in the function until the asynchronous task(s) are completed, and then restarts the function when the result is available.
I made a screencast a while back on understanding JavaScript Generators that you might find helpful:
http://knowthen.com/episode-2-understanding-javascript-generators/
Upvotes: 3