One of the reasons that I tend to dread writing Javascript for anything other than relatively trivial bits of functionality is that I've never found a decent approach for avoiding the callback waterfall when one thing really depends on another. Is there any such approach?
I'm working on a Titanium app right now and bumping into this real world scenario:
I have a set of facilities for which I need to the calculate distance from the user's current location. This entails getting the user's current position (which only needs to happen once) and, while looping through the facility locations, getting the position for each one and calculating the distance. The APIs that retrieve locations (long/lat) are asynchronous so the "easy" approach looks like this (pseudo-code follows):
foreach facility {
API.getCurrentLocation( function( location ) { // async, takes a callback fxn arg
var here = location.coordinates;
API.getFacilityLocation( function( e ) { // async, takes a callback fxn arg
var there = e. coordinates;
var distance = API.calculateFrom( here, there );
});
});
}
Because this is all in a loop, though, I'm calculating my current position each time -- more work than I really need to do. I haven't yet managed to refactor this in such a way that I'm only getting the current location once and still having that location available for the distance calculation.
Given the explosion of languages that support lambdas and closures, I keep thinking that someone must have found an approach to keep these waterfalls manageable, but I have yet to find a good explanation of how to organize such a solution.
Any suggestions or hints?
Any insight would be tremendously appreciated.