JayData.org

How to work with the JayData promise interfaces

Author: Peter Aron Zentai September 18th, 2012


The JayData core supports deferred results, aka promises in all the cases where an async operation is involved. The promise implementation is pluggable so you can chose to work with jQuery.deferred or Q. The client interface is the same regardless of which implementation is selected. Also, you can write you own promise implementation and have it used by JayData (an expert scenario this post will not cover).

Please note that while this example uses the OData provider and the Northwind sample database (published with a WCF Data Service), promise interfaces work across all JayData providers: mongoDB, indexedDB, sqLite or YQL just to name a few.

Prepare your environment

Promise implementations are introduced to the JayData core with the inclusion of their respective adapters in your HTML5 page or JavaScript application.

jQuery.deferred

If you are about to use jQuery.deferred, your script block should look like this:

Q library on the client

Q is a cool, cross layer deferred framework. You can grab it from github. To use Q in the client side your script block should look like this:

Q library on the server with NodeJS

You can get Q with npm. Then:

Working with promises

Now that you have set it up, you can be promised!

Using promise.then and promise.fail instead of result callbacks

The result

CropperCapture[53]

Note that in this simple use case this is equivalent with the following code:

The big difference comes in when you have to work with chained operations: multiple things have to be done, and one operation depends on the result of a previous one. While you can chain operations with success/error callbacks too, the result will be a deep callback chain that is very hard to maintain. Promises help you flatten you code (nesting wise) and make up to a more readable code that is more easy to support on the long run.

Chaining async operations

The following code gets the first two categories (based on default ordering) and then gets their respective products.

The Result

CropperCapture[54]

Waiting for the completion of two or more async operations

The following code gets the list of all supliers while creating a new product line in the database. We’ll get notified when all of these happened.

The Result

CropperCapture[55]