Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break out of chained functions

Tags:

javascript

I have a series of chained functions on an object. For example:

var obj = {};
obj.a = function(){
    console.log('in a');  
    return this;
};


obj.b = function(){
    console.log('in b');  
    return this;
};

obj.c = function(){
    console.log('in c'); 
    return this;
};

obj.a().b().c();

Obviously the result when i look at console is:

 in a
 in b
 in c

But how would I break out of this so that a and b execute but c is never reached?

like image 529
Mark Avatar asked Nov 26 '25 16:11

Mark


1 Answers

The obvious answer is "just don't call c", but I guess that's not an option for some reason.

That aside, you could hack around it by throwing an error from one of the function calls before c, but I wouldn't recommend it. Exceptions are for error handling, not flow control [*].

var obj = {};
obj.a = function(){
    console.log('in a');  
    return this;
};


obj.b = function(){
    console.log('in b');  
    if(shouldBreak) {
      throw new Error('decided to break');
    }

    return this;
};

obj.c = function(){
    console.log('in c'); 
    return this;
};

try {
  obj.a().b().c();
} catch {
  console.log('broke early')
}

[*] unless you're into Python

like image 200
joews Avatar answered Nov 29 '25 04:11

joews



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!