7

I'm having trouble wrapping my head around promises. I'm using the Google Earth API to do a 'tour' of addresses. A tour is just an animation that lasts about a minute, and when one completes, the next should start.

Here's my function that does a tour:

var tourAddress = function (address) {
        return tourService.getLatLong(address).then(function (coords) {
            return tourService.getKmlForCoords(coords).then(function (kml) {
                _ge.getTourPlayer().setTour(kml);
                _ge.getTourPlayer().play();

                var counter = 0;
                var d = $q.defer();
                var waitForTour = function () {
                    if (counter < _ge.getTourPlayer().getDuration()) {
                        ++counter;
                        setTimeout(waitForTour, 1000);
                    } else {
                        d.resolve();
                    }
                };

                waitForTour();

                return d.promise;
            });
        });
    }

This seems to work pretty well. It starts the animation and returns a promise that resolves when the animation is complete. Now I have an array of addresses, and I want to do a tour foreach of them:

$scope.addresses.forEach(function (item) {
      tourAddress(item.address).then(function(){
          $log.log(item.address + " complete");
       });
 });

When i do this, they all execute at the same time (Google Earth does the animation for the last address) and they all complete at the same time. How do I chain these to fire after the previous one completes?

UPDATE

I used @phtrivier's great help to achieve it:

 $scope.addresses.reduce(function (curr,next) {
      return curr.then(function(){
            return tourAddress(next.address)
      });
  }, Promise.resolve()).then(function(){
      $log.log('all complete');
  });
John Slegers
  • 45,213
  • 22
  • 199
  • 169
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112

2 Answers2

6

You're right, the requests are done immediately, because calling tourAddress(item.address) does a request and returns a Promise resolved when the request is done.

Since you're calling tourAddress in a loop, many Promises are generated, but they don't depend on each other.

What you want is to call tourAdress, take the returned Promise, wait for it to be resolved, and then call tourAddress again with another address, and so on.

Manually, you would have to write something like :

tourAddress(addresses[0])
  .then(function () {
     return tourAddress(addresses[1]);
  })
  .then(function () {
     return tourAddress(addresses[2]);
  })
  ... etc...

If you want to do that automatically (you're not the first one : How can I execute array of promises in sequential order?), you could try reducing the list of address to a single Promise that will do the whole chain.

_.reduce(addresses, function (memo, address) {

   return memo.then(function (address) {
         // This returns a Promise
         return tourAddress(address);   
   });

}, Promise.resolve());

(This is pseudo-code that uses underscore, and bluebird, but it should be adaptable)

Community
  • 1
  • 1
phtrivier
  • 13,047
  • 6
  • 48
  • 79
  • 1
    ahh thankyou, I think `reduce` is what I'm looking for. I'll see if i can get it working – Jonesopolis Sep 30 '14 at 16:04
  • 2
    Why the `_.reduce`? You could just as easily do `addresses.reduce` – Benjamin Gruenbaum Oct 01 '14 at 06:38
  • 1
    @BenjaminGruenbaum I was not sure what was the type of $scope.addresses, and whether Array.reduce was supported everywhere (seems to be, though : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) – phtrivier Oct 01 '14 at 07:45
0

It's because you're doing things asynchronously so they'll all run at the same time. This answer should help you rewrite your loop so each address is run after the next one.

Asynchronous Loop of jQuery Deferreds (promises)

Community
  • 1
  • 1
Stephen Gilboy
  • 5,572
  • 2
  • 30
  • 36