npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

switchback

v2.0.5

Published

Normalize callback fns to switchbacks and vice versa

Downloads

260,121

Readme

Switchback

Bower version NPM version     Build Status

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

| | Jump to... | |-----|-------------------------| | I | Usage for Users | II | Usage for Implementors | III | Usage w/ Other Flow Control Libraries | IV | Details | V | License

========================================

Usage

Using a function with a switchback


// So you heard about this new function called `mowLawn`
// which accepts a switchback.  We know it has a `success`
// handler, and a catch-all `error` handler, but turns out
// it also has two others: `gasolineExplosion` and `sliceOffFinger`.

// Let's try it!

// Pass in a switchback:
mowLawn('quickly', 'zigzags', {
  // We can omit the `error` handler because the documentation for `mowLawn` says that it's optional.
  // This varies function-to-function.
  // (i.e. its only purpose is to act as a catch-all if the two explicit handlers are not specified)

  gasolineExplosion: function () {
    // Safety goggles next time.
  },
  sliceOffFinger: function (numFingersLost) {
    // Oh my.
  },
  success: function (dollarsEarned) {
    // Lawn was mowed, everything worked.
  }
});

// Or we can pass in a callback function instead:
mowLawn('quickly', 'zigzags', function (err, dollarsEarned) {
  if (err) {
    // Handle the error, count fingers to figure out what happened, etc.
    // Also don't forget to return early or use `else` or something.
    return;
  }

  // Lawn was mowed, everything worked.
});

// Both are cool.


// Finally, it's worth noting that the return value is an EventEmitter:
mowLawn('quickly', 'zigzags')
.on('gasolineExplosion', function (err) {
  // Safety goggles next time.
})
.on('sliceOffFinger', function (numFingersLost) {
  // Oh my.
})
.on('success', function (dollarsEarned) {
  // Lawn was mowed, everything worked.
})

Implementing a function with a switchback

Adding an optional switchback interface to a function is pretty simple. Just install:

$ npm install switchback --save

Require:

var switchback = require('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('switchback');

function myFunction (stuff, cb) {
  cb = switchback(cb);
  // that's it!

  // All the standard callback things work the same
  if (err) return cb(err);

  // But now you can call custom handlers too:
  if (cb.someHandler) {

  }

  // Mix it up!
  // Table the label!
  // Wear your own name!
  cb(null, 'whatever', 'you', 'want');

  // Make it chainable
  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) {

  // At the very top, upgrade the callback to a switchback.
  // You can also do `var sb = switchback(cb)` to make the distinction explicit.
  cb = switchback(cb);

  // Do your stuff
  // ...


  // If cb was a switchback:
  /////////////////////////////////////////////////

  // Things that trigger the `success` handler:
  return cb();
  return cb(null);
  return cb.success('the results!!!!');
  return cb.success();


  // Things that trigger the `error` handler:
  return cb('bahh!');
  return cb.error('bahh!');
  return cb.error();


  // If cb was a callback function:
  /////////////////////////////////////////////////

  // OK but what about usage with normal node callbacks?
  //
  // If a user of `freeHouseholdPets()` passes in an old-school callback,
  // e.g. function (err, results) {console.log(err,results);}, here's what
  // will get printed to the console in each case:

  cb() // ---> null undefined
  cb(null, 'the results!!!!') // ---> null the results!!!!
  cb.success() // ---> null undefined
  cb.success('the results!!!!'); // ---> null the results!!!!

  cb('bahh!') // ---> bahh! undefined
  cb('bahh!', 'foo') // ---> bahh! foo
  cb.error() // ---> [Error] undefined
  cb.error('bahh!') // ---> bahh! undefined
}


// Now everybody can use a good ole-fashioned callback function:
freeHouseholdPets(function (err, results) {
  if (err) {
    // Something came up, the pets were not freed.
    //
    // Handle the error, but don't forget to return early
    // or use `else` or something..
    return;
  }

  // Pets were freed, we can go about our business
});

// or a switchback:
freeHouseholdPets({
  error: function (err) {
    // Something came up, the pets were not freed.
    // Handle the error.
  },
  success: function (results) {
    // Pets were freed, we can go about our business
  }
});

========================================

Using switchbacks with other flow control libraries

For the examples below, imagine juiceFruit(fruitName, sb) is a switchback-enabled function (i.e. you can pass in exits or a callback for the sb argument).

with async
var fruits = ['apples', 'oranges', 'miracle fruit'];
async.each(stuff, function (fruit, next){

  // do stuff w/ fruit here...  (juice it, eat it, whatever you want)
  juiceFruit(fruit, next);

}, function afterwards(err){
  if (err)  {
    console.error('Oh no I made a mess:',err);
    return;
  }

  console.log('mm mmm fruit');
});
with q promises
// TODO
with generators
// TODO

========================================

License

MIT © 2014 Mike McNeil, Balderdash & contributors

This module is free and open-source under the MIT License.

image_squidhome@2x.png

githalytics.com alpha