What are you in the mood for today?

Thursday, 21 November 2013

Previously we discussed the benefits of the ‘Comb’ library. We will add to our knowledge here, by discussing ‘Promises’. We are not speaking of promises that are too good to be true! Rather that of a client system willing to fulfill or resolve an operation asynchronously, hence a ‘Promise’. We want to use ‘Promises’, to wrap our code sections, so that we don’t cause blocking in error handling. You will find that your code is also cleaner.

In these examples we will be using CoffeeScript, so we can get a flavor of that emerging language that compiles into JavaScript as well. You will also need to install require.js through the NPM. One tricky thing to remember about CS (CoffeeScript) is that even a tab or a space can cause the compiler to resolve something differently.
Here ‘Promise’ has three supported methods that we will cover: errback(), callback(), and resolve().

Now let’s make this even easier: If we use the ‘resolve’ method, we do not have to handle the success and fail code paths separately. Now the ‘callback’ and ‘errback’ methods, are wrapped in a single ‘resolve’ method.

This version of the ‘readFile’ function does the exact same work as the above, but with a lot cleaner code! Now let’s build on this by adding a ‘listener’. Your purpose, is to listen for the resolution/fulfillment of a ‘promise’. We are looking for the task to be completed, or a failure. Using the ‘readFile’ function from above, the following is listening for a successful: You guessed it, a successful file-read.