Simplify async code with generators and promises

Asynchronous code is a necessary part of life when developing in JavaScript. Why not make it easy on yourself?

Start with promises. They reduce the need for callback functions and practically eliminate nested callbacks. If you aren’t already using them, you should be. My favorite library for promises is

Then we have generators. They are a new feature introduced in ES6. You can read more about them here:*

Even when using promises, async code can become unwieldy. Take a look at the following code.

getUser(id).then(function (user) {
  return getCompany(user.companyId).then(function(company) {
    return getUser(company.ceoId);

Assume id is already set and that all functions return promises. The code will return the user object for the CEO of the original user’s company. Take a look at that same function using generators and, a helper library.

co(function *() {
  let user = yield getUser(id);
  let company = yield getCompany(user.companyId);
  return yield getUser(company.ceoId);

Not bad. Generators used with promises gives us code that is nearly identical to async/await. Much easier to follow and read.

If you’re using Bluebird, coroutines provide the same functionality.—function


Now read this

Isolate Scope Helpers

Author’s note - This has changed in Angular 1.2. Directives with isolated scopes will only share this isolated scope with other directives that explicitly request it. It will no longer impact regular directives. Isolate scope is a... Continue →