Last active
          December 22, 2017 09:46 
        
      - 
      
- 
        Save bigs/6442540 to your computer and use it in GitHub Desktop. 
    a very quickly hacked implementation of go's defer in javascript
  
        
  
    
      This file contains hidden or 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 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 | 
  
    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