Before talk about Node.js, promises and ES2015, let me to introduce myself. I am Antonio Bustos, a software engineer focused on Javascript and network applications. Since February 2015, I work at Finametrix in wealth and asset management solutions as full stack javascript engineer. But rarely I am working out of the backend side.

It is going to be a year since I am back at Valencia, my native town, and I should start writing some articles about Javascript. Time is over.

I do not plan to write something very difficult this time, but since Node.js released version 0.12.0 on 6th February 2015, I started convincing my new colleagues at Finametrix to switch (as soon as possible) to new version. Why? Because I knew harmony argument was available in a stable version (it was available in unstable 0.11.x releases).

This argument enables some new V8 features, for example, new block scoping statements, generator functions and promise object. Anyway, after version 4.x, you have harmony features enabled by default. If you are using 0.10, try to upgrade as soon as possible.

Well, something useful that you probably now are generator functions. They can handle in a more readable way asynchronous code, until we reach ES7 in the future.

For example, next callback hell example.

function bar(name, callback) {}
function xyz(name, callback) {}
function baz(name, callback) {}

function foo(callback) {
  bar('bar', function(err, barRes) {
    if (err) {
      callback(err);
      return;
    }
    xyz('xyz', function(err, xyzRes) {
      if (err) {
        callback(err);
        return;
      }
      baz('baz', function(err, bazRes) {
        if (err) {
          callback(err);
          return;
        }
        callback(null, [ barRes, xyzRes, bazRes ]);
      });
    });
  });
}

Can be re-implemented with generators.

function* bar(name) {}
function* xyz(name) {}
function* baz(name) {}

function* foo() {
  const barRes = yield bar('bar');
  const xyzRes = yield xyz('xyz');
  const bazRes = yield baz('baz');
  return [ barRes, xyzRes, bazRes ];
}

For me, less code, avoid callback hell, avoid (callback) error handling,... Performance is a good topic to discuss in another post, but I do not expect big differences.

We need a generator control flow library to manage iterator's next method when the function or promise finishes. co is the library which I use almost everyday. If you like this approach, you can switch to koa to make your next website.

Function generator are very helpful to manage deferred work, but I am used to work with them to handle in a better readable way promises in node.