The best feature that I have encountered with AngularJS is programming async functions. The best example of using async functions is the $http service. To make a web request, the following javascript code can be used:

The $http function returns a promise object. The promise object has a then function which has two arguments: onSuccess callback, onFailure callback. If the web request suceeded, control flows through the onSuccess callback.

The $q service in AngularJS enables the creation of async functions. The typical pattern of async function programming is as follows:

$q.defer() function is used to create a promise object. The resolve() and reject() functions enables passing objects from the promise to the calling function in an async manner.

To help you give a concrete example, we can use the SQLite plugin exposed by ngCordova. We can create a DbService which returns a list of employees as follows:

The above code gets a list of employees and makes it available for the calling function in the form of a Javascript array (employees). The calling function can bind the employees to a scope object as follows:

The scope object can be bound to the UX using ng-repeat directive.

Async functions with AngularJS
Tagged on:

Leave a Reply

Your email address will not be published. Required fields are marked *