How does the $resource `get` function work synchronously in AngularJS?

$resource is not synchronous although this syntax might suggest that it is:

$scope.twitterResult = $scope.twitter.get();

What is going on here is that call to the AngularJS will, after call to twitter.get(), return immediately with the result being an empty array. Then, when the async call is finished and real data arrives from the server, the array will get updated with data. AngularJS will simply keep a reference to an array returned and will fill it in when data are available.

Here is the fragment of $resource implementation where the “magic” happens: https://github.com/angular/angular.js/blob/master/src/ngResource/resource.js#L372

This is described in the $resource documentation as well:

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most case one never has to write a callback function for the action methods.

Leave a Comment