I'm having trouble wrapping my head around promises. I use the Google Earth API to tour addresses. A tour is just an animation that lasts about a minute, and when it ends, the following should begin.
Here is my function that makes the 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; }); }); }
It seems to work very 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 make them for 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 simultaneously. How to connect them to the fire after completing the previous one?
UPDATE
I used @phtrivier 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'); });
javascript angularjs promise angular-promise
Jonesopolis
source share