Switchback
Normalize a callback to a "switchback" and vice versa.
- Allows your functions to "branch".
- Makes usage of branching functions suck less.
- Maintains 100% compatibility with node callbacks.
- Helps keep users of your async functions from "forgetting to return early" andthentimespaceparadox
- Works w/ Node.js and in the browser.
- Table the label, wear your own name.
========================================
Contents
========================================
Usage
Using a function with a switchback
mowLawn('quickly', 'zigzags', {
gasolineExplosion: function () {
},
sliceOffFinger: function (numFingersLost) {
},
success: function (dollarsEarned) {
}
});
mowLawn('quickly', 'zigzags', function (err, dollarsEarned) {
if (err) {
return;
}
});
mowLawn('quickly', 'zigzags')
.on('gasolineExplosion', function (err) {
})
.on('sliceOffFinger', function (numFingersLost) {
})
.on('success', function (dollarsEarned) {
})
Implementing a function with a switchback
Adding an optional switchback interface to a function is pretty simple. Just install:
$ npm install node-switchback --save
Require:
var switchback = require('node-switchback');
And then call switchback()
on the callback at the top of your function, overriding the original value:
cb = switchback(cb);
To enable complete, chainable usage, you should also return the switchback from your function:
return cb;
For example:
var switchback = require('node-switchback');
function myFunction (stuff, cb) {
cb = switchback(cb);
if (err) return cb(err);
if (cb.someHandler) {
}
cb(null, 'whatever', 'you', 'want');
return cb;
}
========================================
Details
Switchback is a JavaScript flow control library. It works alongside async, promises, generators, and conventional Node callbacks to provide support for error negotiation via casefunctions. It also makes your callbacks EventEmitters. You might be familiar with a similar concept from jQuery.ajax
(i.e. $.ajax({ success: foo, error: bar });
). It may be helpful to think about this module as the equivalent of something like async.if()
or async.switch()
.
More examples of exactly what to expect
function freeHouseholdPets (cb) {
cb = switchback(cb);
return cb();
return cb(null);
return cb.success('the results!!!!');
return cb.success();
return cb('bahh!');
return cb.error('bahh!');
return cb.error();
cb()
cb(null, 'the results!!!!')
cb.success()
cb.success('the results!!!!');
cb('bahh!')
cb('bahh!', 'foo')
cb.error()
cb.error('bahh!')
}
freeHouseholdPets(function (err, results) {
if (err) {
return;
}
});
freeHouseholdPets({
error: function (err) {
},
success: function (results) {
}
});
========================================
Using switchbacks with other flow control libraries
with async
with q
promises
with generators
========================================
License
MIT
© 2014
Mike McNeil, Balderdash & contributors
This module is free and open-source under the MIT License.