Skip to content

Instantly share code, notes, and snippets.

@zachlysobey
Last active June 8, 2016 19:52
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachlysobey/6d0f44e3ebc414d2b736 to your computer and use it in GitHub Desktop.
Save zachlysobey/6d0f44e3ebc414d2b736 to your computer and use it in GitHub Desktop.
breakingthings's $q advice

@breakingthings's promise advice

How not to suck at $q

  1. success / error are not promise flow. They're pseudopromise demons. Use then and catch instead.
  2. $q.defer is satan. You should basically never use it. There is an alternative syntax that is superior, $q(function(resolve, reject) {}) but chances are that what you’re working with already returns a promise, and if it does there is absolutely no need for either of these.
  3. Don’t use the promiseFn().then(successFn, errorFn) pattern, as errorFn will only catch errors caused by promiseFn, but not by successFn. Use then(successFn).catch(errorFn) instead. Also note that you can chain several thenables and catch all of them this way, ala then(a).then(b).then(c).catch(errorFn), in which errorFn will handle errors that happen for any of a, b, or c.
  4. Whatever you return from a then-able is turned into a resolving promise. Whatever you throw is turned into a rejecting one. For instance, .catch(function(err){ return err; }) passes the error object along to the next then, it can no longer be caught with catch
  5. var promiseA = promiseFn(); var promiseB = promiseA.then(function(result) { return ‘hi’; }); ... promiseB’s then-able doesn’t propagate back up to promiseA. If you promiseA.then(…) you’re not going to get ‘hi’ as your argument, you’re going to get the same result that promiseB got. Be careful of this, as you’re “forking” the promise chain at this point

More resources

special thanks to hassanbazzi for advice & links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment