Shaun
Shaun

Reputation: 2052

Data request is sometimes asynchronous

This is a follow-up to a question I posted earlier today. I'm going through this book on using AngularJS with Firebase, which lead me to post this question. I found a solution, but what I still don't understand is that the example in the API Documentation for a $firebaseArray doesn't seem to be handling it as an asynchronous request.

var list = $firebaseArray(new Firebase(URL));

// add an item
list.$add({ foo: "bar" }).then(...);

// remove an item
list.$remove(2).then(...);

// make the list available in the DOM
$scope.list = list;

Also, the example from the books seems to treat the request synchronously as well.

# Service
var buildingsUri = FIREBASE_URI + '/buildings';
var ref = new Firebase(buildingsUri);
var buildings = $firebaseArray(ref);

var getBuildings = function () {
  return buildings;
};

...
# Controller
$scope.buildings = syncArraySvc.getBuildings();

How is it that $scope.list in the first example and $scope.buildings in the second example could be properly populated with data when they haven't checked to make sure the request has completed?

Upvotes: 3

Views: 90

Answers (1)

Kato
Kato

Reputation: 40582

The $add and $remove methods return promises. The $firebaseArray() method returns an array with some special functions and properties added. Neither $add or $remove require the data to be loaded locally or depend on the state of the data, so they can be called synchronously. The data is still downloaded asynchronously, of course. So, for example:

var list = $firebaseArray(new Firebase(URL));

// add an item
list.$add({ foo: "bar" }).then(function(ref) {
   console.log('added', ref.key());
});

// remove an item
list.$remove(2).then(function(ref) {
   console.log('removed', ref.key());
});

console.log('list current contains', list.length, 'items');

list.$loaded(function() {
   console.log('after loading initial data, the list contains', list.length, 'items');
});

Assuming the list contains 10 items at load time, and that list is not changed remotely during this code execution, we would see output similar to the following:

list currently contains 0 items
after loading initial state, the list contains 10 items
added abc123
removed xyz456

Additionally, I'd note that this code is probably superfluous. Usually when we see code like this, it's because devs are trying to turn Firebase into a CRUD model. You can probably just return $firebaseArray() there instead and use the existing methods like $getRecord(), et al, instead of artificially wrapping the API in your service.

Upvotes: 1

Related Questions