Skip to main content

Posts

Showing posts from January, 2016

Handling Promises with $q in Angular JS

Old way of async operations

[code lang="javascript"]
function getCurrentUser(callback)
$http.get("/api/users/me")
.success(function(user){
callback(user);
});

//Let assume if you have two functions as below
getCurrentUser(function(user){
//function one
//some task with user
});
getPermissions(function(permission){
//function two
//some task with permissions
});

//If you need this both results simultaneously (Serialized)
//you can use as below as for old method
getCurrentUser(function(user){
getPermissions(function(permission){
//do what you want with users and permissions
//But it contains following issues
//[1] Not Parallelizable
//[2] Not Composable
//[3] Not Dynamic (have to define the structure at runtime)
});
});
[/code]
Better way if you go with Angular JS is service implementation. Its as below;

[code lang="javascript"]
//Then better way is $q
//Service implemenation as below
function getCurrentUser(){
//define deferred
//this is one time use object
var deferred = $q.defer();
//res…