Skip to main content

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();
//resolve object into deferred
$http.get("/api/users/me")
.success(function(user){
deferred.resolve(user);
});
//return promise
return deferred.promise;
}
//Calling it, some what different other than old method
getCurrentUser()
.then(function(user){
//do tasks with user
//Async call
})

//How to make two functions parallelizable
$q.all([getCurrentUser(),getPermissions()])
.then(function(responses){
//returns of user
var user=responses[0];
//returns of permissions
var permissions=responses[1];

//This will call defined methods parallel
//Wait for both methods, without moving to next in program flow
//$q.all doing this magic for us
});

//Following have been separated because to enforce separation of notifier and receiver

deferred.resolve() //notifier (mostly in service side)
promise.then() //receiver (mostly in controller side)

// Some more functions we getting as below
// [1] Send errors like below by notifier
deferred.reject()
// [2] Send progress updates
deferred.notify(...)

//
// Receiver implementation for above as below
//
promise.then(function(){
// to do when Success
},function(){
//[1]
//to do when failure
},function(){
//[2]
//progress (i.e called 0 or more times)
});

//_____________________________________________________________________________________
//
$q.when();
//Can be used for client side caching
myApp.factory("Movies",function($q,$http){

var chachedMovies//will store cached movies
,p//promise that returns when same request called while helper function is executing;

return{
getMovies:function(){
//***
//return cahedMovies else call helper to get data
//***
return $q.when(cachedMovies || p || helper());
}
};

//helper function
function helper(){
var deffered=$q.deffer();
//return the loaded values if this function called while http GET is processing
p = deffred.promise;
//
$http.get("/movies").success(function(movies){
chachedMovies=movies;
deffered.resolve(movies);
});
return deferred.promise;
}
});
[/code]
https://docs.angularjs.org/api/ng/service/$q

Comments

Popular posts from this blog

Turn off/ Hide Details panel/ Information Panel on modern SharePoint lists

Not always we require to show changes done by other which is a mandatory feature in SharePoint online.  What is details pane (aka. Information Pane)? Detail pane/ Information shows information regarding the document if you selected a one or its showing recent changes within a list or library. Follow link to Microsoft documentation about details pane. Bad news: Until Microsoft listen to User Voice , there is no straightforward way to enable disable this even you don't want. Good news: We could write a SharePoint framework extension to hack styles until Microsoft give us a permanent solution. How? I found this sample project (Inject CSS into modern SharePoint pages with React) which could reuse to our purpose. Thanks to Hugo for saving my time.  Steps to awesomeness:  Clone the project Resolve dependencies >  npm i Bundle >  gulp bundle --ship Package >  gulp package-solution --ship Upload package into SharePoint App catalog  

📢 Update -Top 10 Microsoft Teams questions from customers around the world

Over the last 4 months, we’ve traveled to 9 countries on Microsoft Ignite | The Tour meeting and speaking with users like you about Microsoft Teams. The insights and feedback at every location has been invaluable — Thank you. During our travels, there have been 10 questions that have repeatedly surfaced. Below are all of the questions — including the answers too, of course!   Can you restrict access to a specific channel in a team? What are best practices for governance, specifically around team creation, naming, and retention? Can I add guests to my team? If so, how? How does external access/federation work? How is this different to guest access? What functionalities do I get in a hybrid environment? Is Teams available for on-prem environments? How do I configure Direct Routing in Microsoft Teams? Why should I move from Skype for Business to Teams? How do I make this transition? I have existing SharePoint sites that I would like to bring into Teams. Can I do that? I need t

Eliminate Duplicates in Microsoft Flow and Azure Logic Apps

There is no straight forward method or Microsoft Flow action  to eliminate values in a collection like Microsft Excel (as of March 2019). This little hack will help you to eliminate/ remove duplicates and create a collection of unique values. Sample scenario: Need to send daily summarized notification to assigned approved with pending approval items. Sample workflow: Initialize an array Iterate collection of data and append items that are not there in the filtered array Side note: This won't be an option to consider if you too concerned about the performance of the workflow but for the time being its an option to consider.