Created
October 19, 2016 22:22
-
-
Save DroopyTersen/30e33b375a12e29a705a42f323e9c134 to your computer and use it in GitHub Desktop.
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
var middlewarify = function(pre, post) { | |
post = post || function(next) { next() } | |
var doIt = function(next, params) { | |
return pre(next, params); | |
} | |
var func = function(params) { | |
func.use(post) | |
return new Promise((resolve, reject) => { | |
doIt((result) => { | |
resolve(result) | |
}, params); | |
}) | |
}; | |
func.use = function(fn){ | |
doIt = (function(oldDoIt) { | |
return function(next, params) { | |
oldDoIt(fn.bind(this, next), params); | |
} | |
})(doIt); | |
}; | |
return func; | |
}; | |
var preFunc = function(next, params) { | |
setTimeout(() => { | |
console.log("pre"); | |
console.log(params); | |
next("from pre"); | |
}, 100); | |
} | |
var postFunc = function(next, params) { | |
setTimeout(() => { | |
console.log("post"); | |
console.log(params); | |
next("from post") | |
}, 100); | |
} | |
var middleware1 = function(next, params) { | |
setTimeout(() => { | |
console.log("Middeware 1"); | |
console.log(params); | |
next("from m1") | |
}, 100); | |
} | |
var middleware2 = function(next, params) { | |
setTimeout(() => { | |
console.log("Middeware 2"); | |
console.log(params); | |
next("from m2") | |
}, 100); | |
}; | |
var doSomething = middlewarify(preFunc, postFunc); | |
doSomething.use(middleware1); | |
doSomething.use(middleware2); | |
doSomething("from init").then(params => { | |
console.log("Done") | |
console.log(params); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment