Description
Having a background in server side code entering the world of javascript’s asynchronous functional programming took a bit to wrap my head around and understand. Angular has some awesome libraries that let you make rest endpoint requests using $http module. There was a scenario I ran into recently where I needed to make a rest call to get some ip address information and then make another request based off of the information I received. Under normal synchronous programming this is not a problem, but there is no such guarantee with javascript. I needed to finally learn about callbacks and promises. Although they are similar I decided to go with a callback approach, which I will share here.
The basic premise to callbacks is you are passing functions as objects. The object is read and processed at a certain point. After understanding that functions are just objects in javascript the wheels started clicking in my brain and I was able to get my service to work properly. I made a service that handled the multiple http calls and then I just pass that service as a dependency injection of my controller. Below is just psuedo code on how I was able to accomplish this.
[javascript]
//Controller logic
//This makes the call to the service and when the service is done processing what it needs it then processing the function part of this.
$scope.getQuestion() = function() {
MyService.getQuestion(index, function(question) {
$scope.questionVariable = question;
});
}
//Service Logic
this.getQuestion = function(id, cb) {
this.getIPInfo(id, cb, this.retrieveQuestion);
};
this.getIPInfo(id, cb, retrieveQuestion) {
$http.get("http://ipinfo.io").success(function (response){
//On success then we call another function based on what we passed in;
retrieveQuestion(id, cb);
});
};
this.retrieveQuestion = function(id,cb) {
// The cb is the callback from the original controller variable.
$http.getsomething based off geolocation.success(function(data){
// On successful call do some logic and set what we need in the question data
cb(question);
//This now has the var question completely set the way we need it to populate the original function call.
});
};
[/javascript]
Conclusion
Passing functions as objects is really a neat idea. Event driven asynchronous programming is taking me a while to wrap my head around, but it is really powerful and can accomplish the same end goal as synchronous programming — You just need to know how the beast of javascript behaves.