Tuesday, March 12, 2013

Promises I

This is the first post in a series about jQuery deferred objects, and async patterns in general.

A  deferred object is an object with an initial 'pending' state, and two possible final states: 'resolved' or 'rejected'.

Since jQuery version 1.5 the $.ajax() implements the Promise interface , so we'll focus on ajax connections.

Fetch some json data from a webservice

The most basic example of using a promise; just get some data from the server and do something with it.

  • Line 1 initiates the ajax connection to the server. The result from $.getJSON() is a promise, which is a read-only view of a deferred object.
  • Lines 11 & 12 install a couple of success handlers
Of course in this case the callbacks could've been added in the same line as the ajax call, as in


but the point is that the promise is a regular object which you can save, use as arguments of functions, etc.

One important consequence of this is that you can split the ajax initiation event from the use of the ajax result in your code

This pattern allows you to structure better your code; because the client object is completely agnostic about the use of the data.

No comments:

Post a Comment