Skip to content

Instantly share code, notes, and snippets.

@bigs
Last active December 22, 2017 09:46
Show Gist options
  • Save bigs/6442540 to your computer and use it in GitHub Desktop.
Save bigs/6442540 to your computer and use it in GitHub Desktop.
a very quickly hacked implementation of go's defer in javascript
var deferWrap = function (f) {
return function () {
var cbs = [];
var d = function (cb) {
cbs.push(cb);
};
var args = Array.prototype.slice.call(arguments);
args.push(d);
f.apply(this, args);
cbs.forEach(function (cb) {
cb();
});
};
};
var foo = deferWrap(function (x, defer) {
defer(function () {
console.log('deferred action');
});
x += 1;
console.log('x:', x);
});
foo(10);
// x: 11
// deferred action
@julien-f
Copy link

Hey, FYI, I've created a lib for this, feel free to criticize and report issues 😃
https://github.com/JsCommunity/golike-defer

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