Ad
Utilities
Asynchronous
Code
Diff
  • function Chain(){
      this.links = [];
    }
    
    Chain.prototype.link = function link(cb){
      this.links.push(cb);
      return this;
    }
    
    Chain.prototype.run = function run(end){
      if(this.links.length) {
         this.links.shift()(Chain.prototype.run.bind(this, end), end);  
      } else {
          end();
      }
    }
    • function Chain(){
    • this.links = [];
    • }
    • Chain.prototype.link = function link(cb){
    • this.links.push(cb);
    • return this;
    • }
    • Chain.prototype.run = function run(end){
    • var self = this;
    • var next = function(i){
    • return function(){
    • if (i < self.links.length){
    • self.links[i](next(i+1), end); // i++ makes it harder to reason about this line
    • } else {
    • end() // <-- end will not be called unless the chain is explicitly ended in a link
    • }
    • }
    • };
    • next(0)();
    • if(this.links.length) {
    • this.links.shift()(Chain.prototype.run.bind(this, end), end);
    • } else {
    • end();
    • }
    • }