Moving to Silvrback!

Standard

Hi,

After a few years here on WordPress I decided to move my blog over to Silvrback, a new and shiny blogging platform that is perfect for a technical blog which aims at simplicity and at a distraction-free experience.
The big plus is the Markdown editor, leap and bounds ahead of the WordPress post editor… it has always been somewhat painful to write technical posts on it, but now that alternatives are available at cheap prices (and totally managed in the cloud), I decided to go for it.

As I was already moving I also decided to buy a proper domain, so it will be easier to associate the content of my posts to my profile.
Hopefully this will be my last post here and I hope that the few readers I have will continue to follow me at my new home.

Enough already with words, the new URL to bookmark is

http://blog.valeriogheri.com/

As a bonus, I’ve just published a new tutorial about using Microsoft Azure to send out push notifications over to Android devices, so go check it out!

How to secure your HTTP API endpoints using Facebook as OAuth provider

Standard

Heads up!

The blog has moved!
If you are interested in reading new posts, the new URL to bookmark is http://blog.valeriogheri.com/

 

This post is the natural follow-up of my post “How to build and test your Rest API with Node.js, Express and Mocha”.
Here I’ll show you a possible solution to the problem of authenticating your API users via Facebook, accessing some user’s basic info like name, profile pic and email and using the given Facebook access token to secure all your API endpoints.

Solution:

This is quite a common scenario nowadays yet I couldn’t find many useful source of information. So I went ahead and asked a question on StackOverflow (http://stackoverflow.com/questions/15602667/possible-approach-to-secure-a-rest-api-endpoints-using-facebook-oauth). The solution described below is heavily inspired by the answer given by user Tommy Crush, so thanks Tommy!

The logical steps are:

  1. Login via Facebook on your app (either mobile or web) and obtain the Facebook Access Token

  2. Pass the Facebook Access Token to the server (over SSL for the android app, and for the web app just have it redirect to an API endpoint after FB login)

  3. Check the given Facebook Access Token to make sure it is valid by making a graph call to the /me endpoint. Parse the response to get user id and email and cross-reference this with existing users to see if it’s a new or old one.

  4. Now create a random token, store it and associate it to the user id and give the API token back to the requesting app. If you need Facebook for anything other than login, store it too in your DB and associate it with the new api_access_token and your user_id.

  5. For every call hereafter, send the api_access_token to authenticate it. If you need the fb_access_token for getting more info, say retrieveing the list of your user’s friends, you can do so by retrieving it from the DB.

Code:

The code shown below  is taken from my current project ShopWithMe available on GitHub  (https://github.com/vgheri/ShopWithMe) and uses a Node.js + Express.js + MongoDB with mongoose technology stack.

I’ll go into details starting of points 3 and 5. Points 1, 2 and 4 should not be a issue.

Step 3: Verify facebook access token

To verify if the given token is valid we need to make a call to the /me endpoint of the Facebook Graph API located at the URL https://graph.facebook.com/me?access_token=$fb_access_token
The result, if token is valid, is a JSON blob containing the user’s information accessible using this token.
This blob should, at its minimum, look like the following:

{
  "id": "xxxxxx",
  "name": "XXX XXX",
  "first_name": "XXX",
  "last_name": "XXX",
  "link": "https://www.facebook.com/XXX",
  "username": "xxxxxx",
  "gender": "xxx",
  "email": "xxx",
  "timezone": 2,
  "locale": "en_US",
  "verified": true,
  "updated_time": "2013-08-14T09:16:58+0000"
}

Otherwise should we have an error response, that’s the JSON blob we’ll get back:

{
  "error": {
    "message": "XXX",
    "type": "OAuthException",
    "code": XXX,
    "error_subcode": XXX
   }
}

As a hint, if you want to try this on the browser, just go to https://developers.facebook.com/tools/explorer/?method=GET&path=me being logged in with Facebook on your browser. Obtain the Facebook Access Token and then point your browser to the URL https://graph.facebook.com/me?access_token=$fb_access_token , where $fb_access_token is the token you just obtained. You should see a JSON object containing your info if all went well (why shouldn’t it? J)

Point 5:
Point 5 is about securing your API endpoints, making sure that only authenticated users can access the data and authorize the request.
Express.js has a nice and easy way to allow a developer to play with the request pipeline, all that is needed is adding a function in the route declaration.
Let’s see how:
In the file where I defined my routes, I just need to update the routes I want to secure, simply modifying them like this:

BEFORE:
app.get(‘/api/profiles/:userId’, handlers.account.getAccount);

AFTER:
app.get(‘/api/profiles/:userId’, authorisationPolicy, handlers.account.getAccount);

As it should be clear, I just added a function called authorisationPolicy to the route declaration that inside the pipeline is processed ahead of the handlers.account.getAccount function .
Let’s see into detail this authorisationPolicy function:

This function executes its authentication policy and if everything is fine, it calls the Express.js next() function, which takes care of executing the next stage in the pipeline.
If otherwise the request should not be authorized, we can send back an error response.

Conclusion

In conclusion what we have seen is a simple yet effective way to integrate Facebook login into your HTTP API and to secure your endpoints.
The key here is to use the Facebook token to identify your users and then to issue your own API tokens to secure your endpoints.

How we do the hiring process in my team

Standard

Heads up!

The blog has moved!
If you are interested in reading new posts, the new URL to bookmark is http://blog.valeriogheri.com/

 

This post is going to be slightly different from the others you can find here on my blog.
Part of my new job is to hire people and at the moment we are in the process of growing the  development team.
I had already took part to some interviews from the other side of the table, but preparing and leading an interview is something different, as I found out.
In fact, after a couple of interviews where I just sketched out some objectives and questions, I found myself in a position where I was not very capable of comparing the two candidates if not by my intuition and memories from the interview.
That’s why I decided to adopt a sort of lean methodology to use for (and adapt after) each interview.
Obviously there’s nothing groundbreaking in what follows, just some well-known good practice and ideas, but having them written down really helps on focusing and applying them, or at least that’s my experience and opinion.

So why a post such as this? Well, because I’ve seen others around lately and they helped me a lot, so why not give something back to the community and hope to help someone else?

Methodology

Establish your goals and your needs, be realistic and keep an eye on your budget

It may look trivial, but in fact this is one of the toughest things to do during the whole process. Obviously everyone would like to hire the best dev in the town, but it’s not always possible nor desirable. Let’s see why.
First of all, establish your needs trying to be as honest as possible: if you are in the middle of a project, or about to start a new project and are in need of workforce, chances are you won’t have much time to train the new comer, so you probably want to look for a developer who has a certain degree of experience in the technologies related to your project.
The degree of experience that you have to aim for may vary based on your budget, the competences inside your team and the risk/complexity associated to the project,
If instead you are not on a hurry or if you have enough people on the team to take some time to train new comers and the project is not that risky/complex, then you can probably afford to hire a junior developer or someone who is not much experienced in the same technologies used in your team, that will cost you lees money and you will have the incredible chance to train him!
Write down your tech needs based on core technologies that are a must, but also include some “nice to have”: if you know that your team is missing some skill that might come in handy, then a nice to have gain importance.
Finally it is also very important to layout some personality traits: these will need to be tailored on those that already belong to your team.
For example, something close to my experience, if your team works on different projects and technologies, it is important to look for someone who is rather open-minded and has not been long single tech focused, because it’s less likely that he/she will happily accept to have to learn something new in a short amount of time.

Again the word here is trade-off: goals and needs must meet budget and reality. Also remember: talented developers are usually hard to keep in your company if you do not motivate them enough with interesting projects and problems to solve, cool technologies, responsibilities and money.
If you know you won’t be able to provide some of these points, then you might think twice before hiring someone who could potentially quit exactly the moment when you most need workforce!

Search

This is the moment when you have to apply all the criteria identified in the first step, and use the many tools available to search for candidates: e.g. Monster and LinkedIn where you can perform really fine-grained searches.
But don’t forget about one of the most important way of finding great people: by word of mouth!
While reading CV I am often unhappy because the job descriptions are not very useful to me: yes there is a list of keywords, yes the scope of the project is there, but quite rarely it is clearly explained what was the role in the team, the responsibilities and the technologies really used and mastered.
And quite often I found out that if they have been vague it’s because they don’t know much about it. Again this is just my small experience, so take it with a grain of salt.
So when you have to screen lots of CV and profiles, I suggest skipping those who have vague job description: at the end you will have less CV, but better ones and this is really important because now we go to step 3, interviews!

The interview

This is where the fun begins! You found some great people (at least based CV or someone else’s opinion), they are available and interested by your job opening, now it’s up to you to lead the interview in a way that is useful and the less stressful possible (for everyone).
I personally don’t like phone interviews because usually the line is bad, it’s less personal and you don’t get to see the body language of the person, which is something really important to me.
That’s why, if possible, I always choose to set up face to face interviews.
For the moment I have very few rules for this phase, one of these is  that the interview should not be longer than 1 hour, after that everyone starts to lose attention and to be tired. Another good practice is to involve someone else from the team too; at the end of the day this new person will have to integrate with the team and work with other people, and having a second opinion is always a good thing :-)
I like to start by introducing the company, the team, the projects we are working on, the methodologies and technologies we use in the development process, and again I describe the job opening, our needs and goals, just to be sure the other person gets them really clear.
Then I ask the candidate to introduce himself/herself, going through the CV and the past experiences (and here is where you can clarify all those vague job descriptions) .
All of this should take a reasonable amount of time, especially if the candidate is a senior dev.
Finally we get to the technical part of the interview: no live coding, no whiteboard coding, these are the other two rules of my interview. I don’t think that asking someone to write some code in 5 minutes in front of people who judge them can really show skills and qualities.
Therefore I wrote down a set of questions that are more colloquial and open-ended than just “Answer a b or c?”.  There are not many questions and I usually don’t ask all of them but instead I just pick the ones that I think could be more appropriate to the job and to the candidate.
Some of those questions have been written by us, many others are taken from the web and can be easily found by googling “interview questions for $technology_X”. I will list them at the end of the post just because they might help people interested to bootstrap their own list.
There are also a  couple of exercises that do not require to write code, just reasoning. Usually I don’t care if the candidate cannot find the right solution on the first try, as long as they get there after a brief discussion and reasoning together.

A project to be done in autonomy

Yep it’s not yet finished! Yes I said that I don’t like live coding, but that doesn’t mean that I do not care about coding skills, au contraire!
At this point, hopefully, there is a small set of candidates to choose from and a good way to select the right candidate is by assigning a project that should be done in autonomy and that should help the team assess several things, such as coding skills, style and quality of code, usage of project related technologies, approach to code testing and ultimately if the candidate can deliver!
If you have budget, you may think about paying the candidate to do some actual work that you need done, otherwise you can opt for very small project that should take no more than a few hours to complete, but yet they should provide good value and insight.

Conclusions

It’s useful to ask the candidate, at the end of each interview, what is his/her opinion, if some question is unclear or confusing.
At the end it’s important to constantly improve your hiring process if you want to increase the likelihood to find the right people.
Finally, bear in mind that this post is just the fruit of my experience and that is very subject to change in the future. Furthermore it applies well to small teams but I have no idea if this would apply well to big teams or other cases.
However any feedback is always appreciated!

Have fun interviewing!

Valerio

p.s. Here is the list of technical questions, mostly oriented to Asp.Net, C# and the web (HTML5, JavaScript)

Interview Questions

General introductionary questions

  • What is your vision of the position? Why are you interested by this position?

  • What books did you read about software development and methodologies?

  • What did you learn yesterday/this week?

  • What excites or interests you about coding?

  • What are your favorite parts about the developer tools you use?

  • Talk about your preferred development environment. (OS, Editor, Browsers, Tools etc.)

  • If you could master one technology this year, what would it be?

  • What’s the coolest thing you’ve ever coded, what are you most proud of? Can you share with us a code sample that you’re proud of, or that you think represents an important part of your coding philosophy?

  • Can you tell us about a hard problem you’ve had to solve, and how you went about solving it?

  • What’s a hashtable?

HTML5/CSS3 specific questions

  • Consider HTML5 as an open web platform. What are the building blocks of HTML5?

  • What are data- attributes good for?

  • Describe the difference between cookies, sessionStorage and localStorage.

  • What is a CSS pre-processor? Name at least one

Javascript specific questions

  • What is an object in JavaScript?

  • Explain how “this” works in JavaScript  (see exercises #1, #2)

  • Explain AJAX in as much detail as possible

  • What is a closure, and how/why would you use one?

  • What is JSON?

  • Explain how prototypal inheritance works

  • How do you go about testing your JavaScript?

  • How do you organize your code? (module pattern, classical inheritance?) Explain the “JavaScript module pattern” and when you’d use it. Ask about private/public properties of an object

  • Explain the concept behind JavaScript promises

  • Can you do multithread operations in JavaScript?

C# / Asp.Net specific questions

  • Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

  • Can you describe the C# memory model? What’s the difference between value types and reference types?

  • What are the available parameters passing strategies in .Net?

    • What is the ref keyword and what does it mean?

    • What is the difference between a reference object passed as a parameter by value and a reference object passed as a parameter by reference?

    • What is the out keyword and what is its peculiarity?

    • Is it possible to define optional parameters in a method signature? If yes, how and what restrictions apply?

  • Can you describe what the keyword const is used for?

  • Can you describe what the keyword readonly is used for? And what’s the main difference between const and readonly?

  • Linq: What’s the “problem” with the following block of code and how would you solve it?
    var customers = from c in context.Customers
                                  select c;
    var waCustomers = customers.Where (c => c.Region == “WA”);
    var waCustomerIDs = waCustomers.Select (c = c.ID);
    var waCustomerNames = waCustomers.Select (c = c.Name);

  • (Ask this question only if the above one has been correctly answered) When would you write a method that returns an IEnumerable<T> and when a method that returns a IQueryable<Customer> (Answer: if you want to allow for composition)

  • What are the main differences between developing a desktop application and a web application? What problem occur on the web that we don’t on the desktop?

  • Can you describe your workflow when you create a web page? / What is your approach to testing when building a web application?

  • Do you know about Asp.Net MVC? Do you know on what conceptual pillars it has been built on?

  • Asp.Net MVC specific questions:

    • What are the benefits of using MVC over Web Forms?

    • What is Razor and what are the benefits of using it?

    • What is a Filter in MVC?

    • What is the role of a controller in an MVC application?

    • Name a few different return types of a controller action method?

    • What is the significance of ASP.NET routing and what are its benefits?

    • What are the 3 segments of the default route, that is present in an ASP.NET MVC application? Example http://www.test.com/Customer/Details/5

SQL specific questions

  • What is the difference between an inner join and an outer join? (see exercise #1)

  • What’s the difference between a table scan and an index seek?

Exercises

JavaScript

#1

var Stormtrooper = function( number, weakMinded ) {
    this.number = number;
    this.weakMinded = weakMinded;
};

Stormtrooper.prototype.checkForDroids = function() {
    return this.weakMinded;
};

var tk421 = new Stormtrooper( "tk421", true );
tk421.checkForDroids(); // return value?

var checkForDroids = tk421.checkForDroids;
checkForDroids(); // return value?

#2

var deathStarTarget = {
    planet: "Alderaan",
    onClickSuperLaser: function() {
        this.destroy( this.planet );
    },
    destroy: function() {
        // DESTROY IT
    }
};

$( "#button" ).on( "click", deathStarTarget.onClickSuperLaser );

SQL

#1

We have two tables:

A    B

-    -

1    3

2    4

3    5

4    6

Show outputs for:

  1. select * from a INNER JOIN b on a.a = b.b;

  2. select * from a LEFT OUTER JOIN b on a.a = b.b;

  3. select * from a FULL OUTER JOIN b on a.a = b.b;

How to build and test your Rest API with Node.js, Express and Mocha

Standard

Heads up!

The blog has moved!
If you are interested in reading new posts, the new URL to bookmark is http://blog.valeriogheri.com/

 

If you need to build an API, you want it done quickly and simply and you love JavaScript, then this article is for you!
I’m going to show a simple, quick and effective way to build and unit test your API and your routes, using Node.js, Express and a few amazing test libraries: Mocha, SuperTest and should.js that integrate very well together in a natural fashion.
The API style is Rest, that is it leverages URLs and HTTP verbs, but I won’t go much into details in this tutorial.
If you ever used technologies such as WCF, you will be amazed at how much quicker it is to build your API with Node, there’s virtually no machinery to put in place, no service references to update, no WSDL… it’s pretty much just logic to implement!
Of course when you want to design your API around a Rest concept, it is very important to think about the access paths to your resources, they NEED to make sense and to be well structured, otherwise you just end up walking down the good old RPC path.
For a nice intro to this concept, see http://www.slideshare.net/domenicdenicola/creating-truly-res-tful-apis
By the way, in this tutorial I won’t cover advanced topics such as securing the API through HMAC or OAuth solutions.

From words to code:

A nice and free dev environment where to start coding is cloud9 (https://c9.io), as  it offers everything you need and maybe more: a text editor with syntax highlighting, a Node.js environment, a debugger (!), a shell, cloud storage and it connects to your GitHub repository… because you have a GitHub repository, don’t you? We don’t need more than that to write our first API, so let’s start!

Ok we want to write a HTTP API, so we obviously want our API to be accessible via some sort of webserver, but as you may already know, Node.js doesn’t come with its own webserver.
Instead it comes with some facilities built-in; on top of these facilities lies Express.js, the web server of choice for this tutorial. Express.js (http://expressjs.com/) describes itself as a web application framework for node, and I think you should use Express too, as it is a solid and well tested piece of software, easy to setup and test.

After reading some tutorials around, I came up with a structure of 4 short files  that setup and run the API:

  1. config.js exports an object that contains all configuration keys and values, pretty much like web.config in an Asp.Net web app. Following this line we can think about having a config-debug.js  and a config-release.js. We’ll see later why.

  2. routes.js exports a setup function that takes care of declaring the routes and the handlers that will manage each request.

  3. server.js where we configure Express and we export a start function that takes care of setting up the routes and starting the web server

  4. index.js is the entry point of our API. It uses pretty much everything we have defined so far to start the logger (my logger of choice is winston), to connect to a database, if present, and to finally start the Express server.

config.js

routes.js

As you can see, setup expects two parameters: app is the Express app and handlers is an object that maps to a set of functions that handles user requests. Each of these functions accepts as parameters the request and response objects: e.g.

function handleCreateAccountRequest(req, res) { … }

server.js

The first part is just some standard Express setup + Express logging.
Now we can see clearly what the parameters for routes.setup are: app is just the Express instance and handlers contains two objects that point to the different handlers that will be able to handle API requests.
Finally, after declaring and exporting the start function, this module exports the Express instance, which will be used in the tests.

index.js

As already said, index.js is the entry point, that means our API will be executed by running the command

$ node index.js

We can easily configure the API logger using winston and the configuration file, we connect in this case to MongoDB using mongoose, a fantastic tool, and then we start the server using the freshly exported function.
That’s it, you don’t need anything else to setup your API along with a solid logger and a database connection.

Ok I have an API but… how do I test it?

The test framework of choice for this tutorial is Mocha (http://visionmedia.github.io/mocha/) along with Supertest for HTTP assertions (https://github.com/visionmedia/supertest) and Should.js for BDD style tests (https://github.com/visionmedia/should.js). Mocha is a great choice because it makes async test natural and fluent.

The purpose here is to unit test our routes  (integration tests) and to build the tests so that we will be able to read our test and the results as if they were plain English sentences!
Let’s create a folder named “test” where we will place our test files and our mocha.opts configuration file where we can specify the output style for our tests.
Finally we can create our unit tests for the routes in a file called “test/routes.js”.

The structure of a test with Mocha is simple and verbose:

So if you try and read the test, it would come out something like:
Describe Routing, describe Account, it should return error trying to save duplicate username, it should correctly update an existing account, and so on.
To add more test, simply add more describe or it functions, and that’s it!

To execute the tests, start your api with

$ node index.js

and then in another shell run

$ mocha

as by default mocha will run everything in /test off of your main project.

If you want to run your test by typing

$ npm test

then all you have to do is to create a makefile and can even be as follows:

then add the following lines to your package.json file:

“scripts”: {
“test”: “make test”
}

and that’s the result (note that in the screenshot I have more tests as it’s taken from an actual project of mine)

Mocha test output with BDD style

Mocha test output with BDD style

That’s it, pretty easy, isn’t it?

Javascript promises and why jQuery implementation is broken

Standard

Introduction to Javascript promises

Callbacks: a classic approach to async

Callbacks are Javascript classic approach to collaborative asynchronous programming.
A callback is a function object that is passed to another function as a parameter and that  later on must be invoked under some circumstances: for example when an asynchronous function successfully completes a task, it invokes the callback function to give back control to the function that was previously executing, signaling that the task has completed.
Callbacks are easy to use, but they make the code less readable and messier, especially if you have few of them one after another using anonymous functions:

Small example

function invokingFunction() {
    // some stuff
    asyncFunction(function(data) { // the first callback function
                   anotherAsyncFunction(function() { // the second callback function
                          //more stuff
                   });
             });
}

This pattern can lead to what is known as the “pyramid of doom”, especially when using jQuery’s mouse event handlers combined with async operations like $.get or $.post.

Javascript promises: the specification

To fix this and other problems (as we’ll see) with callbacks style of code, a specification has been proposed and it is known under the name CommonJS Promises/A. Let’s see what it says:

A promise represents the eventual value returned from the single completion of an operation. A promise may be in one of the three states, unfulfilled, fulfilled, and failed. The promise may only move from unfulfilled to fulfilled, or unfulfilled to failed. Once a promise is fulfilled or failed, the promise’s value MUST not be changed, just as a values in JavaScript, primitives and object identities, can not change (although objects themselves may always be mutable even if their identity isn’t). The immutable characteristic of promises are important for avoiding side-effects from listeners that can create unanticipated changes in behavior and allows promises to be passed to other functions without affecting the caller, in same way that primitives can be passed to functions without any concern that the caller’s variable will be modified by the callee.
[...]
A promise is defined as an object that has a function as the value for the property ‘then':
then(fulfilledHandler, errorHandler, progressHandler)
Adds a fulfilledHandler, errorHandler, and progressHandler to be called for completion of a promise. The fulfilledHandler is called when the promise is fulfilled. The errorHandler is called when a promise fails. The progressHandler is called for progress events. All arguments are optional and non-function values are ignored. The progressHandler is not only an optional argument, but progress events are purely optional. Promise implementors are not required to ever call a progressHandler (the progressHandler may be ignored), this parameter exists so that implementors may call it if they have progress events to report.
This function should return a new promise that is fulfilled when the given fulfilledHandler or errorHandler callback is finished. This allows promise operations to be chained together. The value returned from the callback handler is the fulfillment value for the returned promise. If the callback throws an error, the returned promise will be moved to failed state.

It’s very easy to find blog articles and tutorials online, especially around jQuery Deferred object, and almost all of them show how to do callback aggregation using the “then” function to attach callbacks to a promise, whether for success or for errors (or even to signal that an operation has made some progress). When the promise transitions state, the callbacks will be called, that’s as simple as that.
After reading a lot, I thought I knew enough about promises, but then I stumbled upon this page (https://gist.github.com/3889970) by Domenic Denicola, titled “You’re Missing the Point of Promises”, and after reading it I really had the feeling I was missing it entirely!

What promises are really about

As the previously linked page states, Javascript promises are not just about aggregating callbacks, but actually they are mostly about having a few of the biggest benefits of synchronous functions in async code!
Namely

  1. function composition: chainable async invocations
  2. error bubbling: for example if at some point of the async chain of invocation an exception is produced, then the exception bypasses all further invocations until a catch clause can handle it (otherwise we have an uncaught exception that breaks our web app)

To quote Domenic:

The point of promises is to give us back functional composition and error bubbling in the async world. They do this by saying that your functions should return a promise, which can do one of two things:

  • Become fulfilled by a value
  • Become rejected with an exception

And, if you have a correctly implemented then function that follows Promises/A, then fulfillment and rejection will compose just like their synchronous counterparts, with fulfillments flowing up a compositional chain, but being interrupted at any time by a rejection that is only handled by someone who declares they are ready to handle it.

That is, promises have their foundation in this “then” function, if this is broken than the whole mechanism is broken. And that is exactly what is happening with jQuery’s implementation, let’s see why with the help of an explicative (I hope!) code example.

Why jQuery promises are broken

The problem with jQuery’s implementation (up until version 1.9) is that it doesn’t respect the second part of the specification, “This function should return a new promise…”, that is “then” doesn’t return a new promise object when executing one of the handlers (either the fullfillment, the rejection or the progress handler).

This means we cannot do function composition as we don’t have a “then” function to chain to, and we won’t have error bubbling due to a broken chain, the two most important points about this spec.
Finally, what we have is just callback aggregation.

JsFiddle examples

The following fiddles show a simple chain of async functions.
I’m simulating the case where the original promise is fulfilled, the fulfillment handler is invoked, gets the data and then throws an exception in response to it. The exception should be handled by the first rejection handler down the chain.

The first fiddle  is not working as expected: the rejection handler is never invoked and the error bubbles up to the app level, breaking it. Below I show the console reporting the uncaught error:

Uncaught errors

Uncaught errors

Next fiddle  behaves as expected, with the rejection handler correctly invoked. The way to quickly “fix” the broken implementation is to wrap the handler with a new Deferred object that will return a fulfilled/rejected promise, that can be later used for chaining, for example. Below we see the  console showing no uncaught errors.

No errors

No errors

Alternatives

As we have seen, until at least version 1.9.0, jQuery can’t do pomises properly out of the box, but there are several alternatives libraries on the market such as Q, rsvp.js and others, that adhere completely to the specification.

Conclusion

Promises are the present and the future of Javascript asynchronous operations, they provide an elegant and readable code and more importantly they allow function composition and error bubbling, making async more similar to sync programming style, thus making the life of a developer a little bit easier!
I said that Promises are the future of Javascript async programming because Harmony, the next version of Javascript, will allow for great stuff combining promises with Generators. To see a sneak peek preview on how powerful these two concepts can be if used together, point your browsers to http://www.taskjs.org !

Credits

Again, credits to Domenic Denicola for writing this post  and to all the ones who commented and posted examples that helped me understand, notably user jdiamond!