AngularJS allows to define async functions. An example is the $http service. HTTP service calls an API and returns a response as a promise.
$http.get(url) .then(function(res){ // handle the response }, function(res){ // handle the error });
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.
$scope.callDb = function () { var deferred = $q.defer(); promise.then(function(res){ var someObj = {}; deferred.resolve(someObj); }, function(err){ var errObj = {}; deferred.reject(errObj); }); return deferred.promise; };
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.
app.service('DbService', function ($q, $cordovaSQLite) { this.get = function() { var q = $q.defer(); var query = "SELECT idemployee, name from employee"; var db = $cordovaSQLite.openDB("employee.sqlite", 0); $cordovaSQLite.execute(db, query, []).then(function (res) { var employees = []; for (index = 0; index < res.rows.length; index++) { employees.push(res.rows.item(index)); } q.resolve(employees); }, function (err) { q.reject(null); }); return q.promise; }; });
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.
function get() { DbService.get() .then(function(employees){ $scope.employees = employees; }); }
Bind the Angular’s scope object to a table using ng-repeat directive.