Skip to content

Instantly share code, notes, and snippets.

@mrjoelkemp
Last active December 22, 2017 09:48
Show Gist options
  • Save mrjoelkemp/9118137 to your computer and use it in GitHub Desktop.
Save mrjoelkemp/9118137 to your computer and use it in GitHub Desktop.
Go-style defer without dependency injection
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);
});
@julien-f
Copy link

julien-f commented Dec 22, 2017

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment