Created
December 24, 2013 13:06
-
-
Save HerringtonDarkholme/8113104 to your computer and use it in GitHub Desktop.
Inspired by KOA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// middlewares: array of generator function | |
function compose(middlewares) { | |
return function *() { | |
var i = middlewares.length; | |
var prev = function *(){}; | |
var current; | |
while (i--) { | |
current = middlewares[i]; | |
prev = current(prev); | |
} | |
yield *prev; | |
}; | |
} | |
function run(gen) { | |
var result = gen.next(); | |
if (result.value) | |
run(result.value); | |
// if it return, gen has no next method | |
if (!result.done) | |
gen.next(); | |
} | |
var middlewares = [ | |
function *(next) { | |
console.log('enter first'); | |
yield next; | |
console.log('leave firt'); | |
}, | |
function *(next) { | |
console.log('enter second'); | |
yield next; | |
console.log('leave second'); | |
}, | |
function *(next) { | |
console.log('enter third'); | |
yield next; | |
console.log('leave third'); | |
}, | |
function *(next) { | |
console.log('end'); | |
} | |
]; | |
run(compose(middlewares)()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment