Last active
December 22, 2017 09:48
-
-
Save mrjoelkemp/9118137 to your computer and use it in GitHub Desktop.
Go-style defer without dependency injection
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 deferrable = function (cb) { | |
function getFunctionBody(code) { | |
var functionDef = code.match(/\{(.|[\r\n])+\}/); | |
// Strip body of all useless chars | |
return functionDef[0].replace(/\{|\}/g, '') | |
} | |
var | |
// Grab the entire defer() block | |
deferCode = cb.toString().match(/defer\((.|[\r\n])+\}+\)/), | |
// Grab the deferred function's body | |
functionBody = getFunctionBody(deferCode[0]), | |
toDefer = new Function(functionBody); | |
// Strip out the defer call | |
cb = new Function(getFunctionBody(cb.toString().replace(deferCode[0], ''))); | |
cb(); | |
toDefer(); | |
} | |
deferrable(function () { | |
defer(function () { | |
console.log('bar'); | |
}) | |
console.log(2); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, FYI, I've created a lib for this, feel free to criticize and report issues 😃
https://github.com/JsCommunity/golike-defer
Well it's not exactly the same because I do use dependency injection.