Skip to content

Instantly share code, notes, and snippets.

@oklai
Created December 31, 2014 03:47
Show Gist options
  • Save oklai/3613ce9bfbae3157f7b4 to your computer and use it in GitHub Desktop.
Save oklai/3613ce9bfbae3157f7b4 to your computer and use it in GitHub Desktop.
Koa "yield next" simple implement
'use strict';
var co = require('co');
function App () {
this.gens = [];
}
App.prototype.use = function (gen) {
this.gens.push(gen);
};
App.prototype.init = function () {
var self = this;
var gens = self.gens;
var fn = gens[gens.length - 1];
for (var i = gens.length - 2; i >= 0; i--) {
fn = gens[i].call(self, fn);
}
var p = co(fn);
p.then(function () {
console.log('do something after all done...');
});
};
// use
var app = new App();
app.use(function* fn1 (next){
console.log('>> Run A');
yield next;
console.log('<< Run A');
});
app.use(function* fn2 (next){
console.log('>> Run B');
yield next;
console.log('<< Run B');
});
app.use(function* fn3 (next){
console.log('>> Run C');
yield next;
console.log('<< Run C');
});
app.use(function* fn4 (next){
console.log('>> Run D');
});
// run
app.init();
// return:
// >> Run A
// >> Run B
// >> Run C
// >> Run D
// << Run C
// << Run B
// << Run A
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment