Data request is sometimes asynchronous

This is a follow-up to the question I posted earlier today. I am going through this book about using AngularJS with Firebase which leads me to post this question . I found a solution, but I still don't understand that the example in the API Documentation for$firebaseArray

doesn't look to handle 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;

      

In addition, the example from the books also processes the request synchronously.

# 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();

      

What does $scope.list

the first example look like and $scope.buildings

the second example can be correctly populated with data if it hasn't been checked to make sure the request is complete?

+3


source to share


1 answer


The $ add and $ remove methods return promises. The $ firebaseArray () method returns an array with some special functions and added properties. Neither $ add nor $ remove require the data to be loaded locally or dependent on the state of the data, so they can be called synchronously. Of course, the data is loaded asynchronously anyway. 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 remotely modified while this code is running, we will see output similar to the following:



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

      

Also, I would like to point out that this code is probably redundant. Usually when we see code like this, it is because the developers are trying to turn Firebase into a CRUD model. You can probably just return $ firebaseArray () instead and use existing methods like $ getRecord () and others instead of artificially wrapping the API into your service.

0


source







All Articles