Skip to content

Instantly share code, notes, and snippets.

@DarrylD DarrylD/koa-example.js
Last active Jan 3, 2016

Embed
What would you like to do?
Made a lengthier example on Koa's flow and how it uses generators. This is just demonstrating how the middleware stacks and uses yield opposed to using callbacks like in ExpressJS. https://github.com/koajs/koa
//Koajs example
var koa = require('koa');
var app = koa();
//Middleware cascading
app.use(function * (next) {
//Some stuff will happen here first
console.log('FIRST execution')
yield next; //goes to next generator downstream
//this is the final function-remains to be executed
//this will be the last piece of code to be executed since no more generators are up stream
console.log('SIXTH execution (continuing remaining of FIRST)');
//kills the server since we're done (no need to kill, this is just for demo purposes)
process.exit("status")
});
app.use(function * (next) {
//do more stuff here
console.log('SECOND execution')
yield next; //next generator downstream..
//coming back up stream... finishing this function
console.log('FIFTH execution (continuing remaining of SECOND)')
});
app.use(function * (next) {
//now some stuff will happen here SECOND
console.log('THIRD execution')
yield next; //goes to the last generator downstream
//remaining of this function will execute then go back upstream
console.log('FORTH execution (continuing remaining of THIRD)')
});
// response
app.use(function * () {//notice how no next param is passed
//since this is the last generator, finishes this function and goes upstream
console.log('Response... and going back upstream')
// this.body = 'Hello World';
});
app.use(function * () {
//this isn't executed, but why??
//the previous didn't "yield next"
console.log('another response?')
this.body = 'Bye bye world :(';
});
app.use(function * (next) {
//this isn't executed either, but why??
//the stream already went back up
yield next
console.log('I dont get to run either')
});
app.listen(3000);
console.log('========== starting 3000 ==========');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.