Posts tagged ‘promises’

Promise Objects in JavaScript

2013-10-07 21:48

JavaScript’s default mode of operation is to rely heavily on callbacks: functions invoked when a longer operation (such as network I/O) finishes and delivers result. This makes it asynchronous, which is a notably different programming style than using blocking operations contained within threads (or their equivalents, like goroutines in Go).

Callbacks have numerous problems, though, out of which the most severe one is probably the phenomenon of “marching to the right”:

  1. doSomething(withTheseArgs, function(result) {
  2.     theDoSomethingElse(function() {
  3.         nowDoThis(toThat, function(result) {
  4.             andThen(function() {
  5.                 stop(hammertime, function(result) {
  6.                     // ...and so on...
  7.                 });
  8.             });
  9.         });
  10.     });
  11. });

When using the (still) common style of providing a callback as the last argument to a function initiating an asynchronous operation, you get this annoying result of ever-increasing indentation as you chain those operations together. It feels like the language itself is telling you that it was not designed for such a complex stuff… Coincidence? ;)

But it gets worse. Operations may fail somewhere along the way, which is something you’d probably like to know about. Depending on the conventions your project, framework or environment uses, this could mean additional boilerplate inside the callbacks to distinguish success from error cases. This is typical in Node.js, where first argument of callback represents the error, if any:

  1. fs.readFile('/etc/passwd', 'utf8', function (err,data) {
  2.   if (err) {
  3.     return console.log("Sorry, no hacking for you (" + err.message + ")");
  4.   }
  5.   console.log(data);
  6. });

Alternatively, you may be asked to provide the error handler separately; an “errback”, as it’s sometimes called. Splitting the code into small parts is great and everything, but here it means you’ll have two functions as arguments:

  1. doSomething(withThis, function(result) {
  2.     // ...
  3. }, function(error) {
  4.     // ...
  5. });

Giving them names and extracting somewhere outside may help readability a little, but will also prevent you from taking advantage of one of the JavaScript’s biggest benefits: superior support for anonymous functions and closures.

Tags: , , , ,
Author: Xion, posted under Programming » 3 comments
 


© 2017 Karol Kuczmarski "Xion". Layout by Urszulka. Powered by WordPress with QuickLaTeX.com.