diff --git a/lib/circuit.js b/lib/circuit.js index 42f1e338..2dc50c80 100644 --- a/lib/circuit.js +++ b/lib/circuit.js @@ -9,7 +9,8 @@ const fallbackFunction = Symbol('fallback'); class CircuitBreaker { constructor (action, options) { - this.action = action; + if (typeof action !== 'function') this.action = () => action; + else this.action = action; this.options = options; this.status = new Status(); this.Promise = options.Promise; @@ -35,8 +36,10 @@ class CircuitBreaker { } fire () { + const args = Array.prototype.slice.call(arguments); + if (this.open || (this.halfOpen && this[halfOpenAttempted])) { - return failFast(this, Array.prototype.slice.call(arguments)); + return failFast(this, args); } this[halfOpenAttempted] = this.halfOpen; @@ -47,7 +50,7 @@ class CircuitBreaker { }, this.options.timeout); - this.action.apply(this.action, arguments) + this.Promise.resolve(this.action.apply(this.action, args)) .then((result) => { succeed(this); resolve(result); diff --git a/test/test.js b/test/test.js index 806172e3..1151457e 100644 --- a/test/test.js +++ b/test/test.js @@ -25,6 +25,33 @@ test('Passes arguments to the circuit function', (t) => { .catch(t.fail); }); +test('Works with functions that do not return a promise', (t) => { + const breaker = circuitBreaker(nonPromise); + + breaker.fire() + .then((arg) => t.equals(arg, 'foo')) + .then(t.end) + .catch(t.fail); +}); + +test('Works with non-functions', (t) => { + const breaker = circuitBreaker('foobar'); + + breaker.fire() + .then((arg) => t.equals(arg, 'foobar')) + .then(t.end) + .catch(t.fail); +}); + +test.skip('Works with callback functions', (t) => { + const breaker = circuitBreaker(callbackFunction); + + breaker.fire(3, 4) + .then((arg) => t.equals(arg, 7)) + .then(t.end) + .catch(t.fail); +}); + test('Fails when the circuit function fails', (t) => { const expected = -1; const breaker = circuitBreaker(passFail); @@ -136,3 +163,10 @@ function slowFunction () { }); } +function nonPromise () { + return 'foo'; +} + +function callbackFunction (x, y, callback) { + callback(x + y); +}