Skip to content
Justin edited this page Jul 30, 2014 · 12 revisions

General

  • All UI strings should be added to the _locales descriptors (e.g. _locales/en/messages.json) and retrieved using the i18n service
  • Set up your editor to use the provided settings:
  • Prefer for over forEach
  • Use short but descriptive variable names, e.g. user not u
  • Start and continue chains on a new line on the same column, e.g.:
service.promise()
  .then(function() {
    console.log('Here');
  })
  .catch(function() {
    console.log('Failed');
  });

… not:

service.promise()
  .then(function() {
    console.log('Here');
  }).catch(function() {
    console.log('Failed');
  });

Angular

Refer to mgechev/angularjs-style-guide to begin with, then:

  • Use angular.service over angular.factory unless the service needs to return a primitive or a function (full discussion)

Promises

service.promise()
  .then(function() {
    return anotherService.promise();
  })
  .catch(function(err) {
    console.log(err);
  });

… not:

service.promise()
  .then(function() {
    anotherService.promise();
  })
  .catch(function(err) {
    // Will never be called if `anotherService#promise` fails as JS implicitly
    // adds a `return undefined` (a value), which will be fulfilled (rather
    // than rejected)
    console.log(err);
  });
  • Always make sure a rejection handler exists somewhere in the chain, i.e. if your function cares about unexpected errors, add a .catch, otherwise, throw them up the stack by making sure a promise is returned, e.g.:
a.promise()
  .then(function() {
    return b();
  })
  .catch(function(err) {
    // Handle unexpected errors in `b`
    console.error(err);
  });

function b() {
  return c.promise()
    .then(function() {
      // Return promise to throw any unexpected errors
      return d.promise();
    });
};
  • Consider using named functions instead of anonymous inner functions in promises handlers, baring in mind a promise will always return a single value/promise, that will be passed as an argument to your handler, e.g.:
function processResult(result) {
  return result.processed = true;
};

function logResult(result) {
  console.log(result);
};

function handleError(err) {
  console.error(err);
};

a.promise()
  .then(processResult)
  .then(logResult)
  .catch(handleError);
Clone this wiki locally