Monday, July 29, 2013

Promises in AngularJS

Today I was working on the front end and discovered that I had a race condition while fetching data from two URLs.
I was doing something like this
$http.get(firstUrl).success(function(data){
// initialize $scope.data1 and some other work
}
$http.get(secondUrl).success(function(data){
// initialize $scope.data2 and some other work
}
scope.doSomething($scope.data1, $scope.data2);
The results from doSomething were flaky and I realized, I’d been counting on both http.get’s returning in the same order when in case that was not always the case.
To cut a long story short, I discovered the solution was to use AngularJS promises to ensure that both the http operations were completed before the doSomething() function was called. There’s a lot of stuff on the subject on Stack Overflow and other places especially on more complex scenarios but I couldn’t find a nice concise snippet for my very simple case. So here goes
var myCtrl = function ($scope,$http,$window,$q) {
$scope.firstDataPromise = $http({
method:’GET’
,url:$scope.firstDataRecordUrl
});
$scope.secondDataPromise = $http({
method:’GET’
,url:$scope.secondDataRecordUrl
});
$q.all([
$scope.firstDataPromise
,$scope.secondDataPromise
])
.then(function(data){
//data is an array of objects. The first element in the array is result
// of executing the first promise and the second …
$scope.doSomething(data);
});
}

No comments:

Post a Comment