增强诺言

Restangular uses enhanced promises when returning. What does this mean? All promises returned now have 2 additional methods and collection promises have 3. These are the methods:

  • call(methodName, params*): This will return a new promise of the previous value, after calling the method called methodName with the parameters params.
  • get(fieldName): This will return a new promise for the type of the field. The param of this new promise is the property fieldName from the original promise result.
  • push(object): This method will only be in the promises of arrays. It's a subset of the call method that does a push.
  • $object: This returns the reference to the object that will be filled once the server responds a value. This means that if you call getList this will be an empty array by default. Once the array is returned from the server, this same $object property will get filled with results from the server.

I know these explanations are quite complicated, so let's see an example :D.

var buildings = Restangular.all("buildings").getList();

// New promise after adding the new building
// Now you can show in scope this newBuildings promise and it'll show all the buildings
// received from server plus the new one added
var newBuildings = buildings.push({name: "gonto"});

var newBuildingsSame = buildings.call("push", {name: "gonto"});

// This is a promise of a number value. You can show it in the UI
var lengthPromise = buildings.get("length");

lengthPromise.then(function(length) {
  // Here the length is the real length value of the returned collection of buildings
});