1

Is it possible to do something like this:

var citiesPromise = citiesService.getCities();
var usersPromise = usersService.getUsers();

citiesPromise.then(function(citiesResult) {
  // cities will load very quick, and I can do something with them
);

$q.all([citiesPromise, usersPromise]).then(function(results) {
  // users will probably load after cities, but both results must be available
);

In other words, I need a promise that will behave as an event dispatcher, and every 'then' call on that promise is as if an event listener was added to that promise. When promise is resolved or rejected, all event listeners are notified.

Can this be achieved, or should in this case stick only to the '$q.all' as a single point where all results are processed?

What would I gain by doing this? Maybe in this case not much, but if I was to have 10 or more ajax calls, it would be cool if a page loads gradually, not wasting time waiting for http requests...

AndroC
  • 4,758
  • 2
  • 46
  • 69

2 Answers2

8

Your code looks pretty good. The $q.all() will execute one time once everything is done. But all then() functions will execute when the promises they are attached to are resolved. So yes multiple then() functions are okay as long as they are all independent of each other.

The gain of doing this is the gradual page load that you want. You can have certain things wait for everything, but other items could start to work.

claydiffrient
  • 1,296
  • 3
  • 19
  • 35
0

Just return catch your promise from citiesSerivce inside the function in your .then() and return a promise from it.

The gain would be that you could ensure all data is loaded before the page finishes loading or binding to data you expect to be in the results

PW Kad
  • 14,953
  • 7
  • 49
  • 82