AngularJS allows to define async functions. An example is the $http service. HTTP service calls an API and returns a response as a promise.

Retrieve the result from the Promise object using then function. The function has two arguments: onSuccess callback and onFailure callback.

The $q service in AngularJS creates a promise using the defer function.

Pass the result using the resolve function. If there is an error, pass the error using reject function.

I want to give a concrete example. Cordova has a SQLite plugin (ngCordova). Create a DbService that returns a list of employees.

In the above example, DbService is an Angular service. We have a SQL that retrieves a list of employees. SQLite plugin has an execute function which queries the database using the SQL. The plugin returns a promise. Retrieve a list of employees from the promise. And return a new promise using Angular’s $q service.

Call the DbService to get the employee list. The get method returns a promise. From the then function of the promise, we set the employees to the scope object.

Bind the Angular’s scope object to a table using ng-repeat directive.

Async functions with AngularJS
Tagged on:     

Leave a Reply

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