You are here

ES6

From Javascript Callbacks to Promises to Generators and Coroutines

Corey Pennycuff's picture

JavaScript has always been a powerful language, but it is not always pretty to look at. ES6 has also greatly improved the syntax of the language, and although it's not perfect, it's not that bad, either. Some of JavaScript's limitations are also its strengths, which is what we will see when we examine the JavaScript coroutine pattern.

Javascript is single-threaded. It is also event-driven, so that many of its functions use a callback pattern. Unfortunately, the callback pattern is ugly and cumbersome in code. Promises improved the callback pattern slightly, but it is still not as clean as it could be. The generator pattern is the latest incarnation of data-flow syntax. To get an intuitive feel for the differences between the different approaches, look at the following code examples:

The callback method:

fs.readFile('filename.txt', 'utf8', function(err, data) {
  if (err) {
    // Something failed.
  }
  else {
    // Do something with 'data'.
  }
});

Tags: 

Promisify A Callback Function Without 3rd Party Libraries

Corey Pennycuff's picture

I was recently working on some code in which I wanted to use Promises, but all that I had was callback-centric code. In the past, I have imported libraries such as bluebird for this particular problem, but now that seems like a bit of overkill to get just one function. I'm already using ES6, so I don't need a polyfill in order to use Promises; all that I want is a simple promisify() function. Importing an entire library for one function is, IMO, wasteful. Besides, it's more fun to write (and therefore understand at a deeper level) your own implementation, so that's what I did.

If you don't care about why this code works, then you can see it in its completed form below. If you are actually curious as to how I came up with it, then read on and I will explain it to you. The finished code is as follows:

/**
 * Convert a callback-based function into a promise.
 **/
function promisify(fn) {
  return function() {
    let args = Array.from(arguments);
    return new Promise((resolve, reject) => fn(...args, (error, content) => error ? reject(error) : resolve(content)));
  };
}

Tags: 

Subscribe to RSS - ES6