You are here

Generator

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: 

Subscribe to RSS - Generator