My JavaScript code contains quite a few asynchronous functions. For example, I'm using D3.JS to read a CSV file, and I'm connecting to the Google Maps API to find the driving directions between two addresses.
I'm using this answer on StackOverflow to wait until the asynchronous function is complete (to avoid return variables with a undefined
value). However, because I have a lot of asynchronous functions, I have a lot of nested anonymous callback functions:
carDirections(from, to).done(function(car) {
transitDirections(from, to).done(function(train) {
// carDirections and trainDirections have similar anonymous callback functions.
function carDirections(from, to) {
var dfd = $.Deferred();
var directionsService = new google.maps.DirectionsService;
directionsService.route({
origin: from,
destination: to,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
dfd.resolve(response.routes[0].legs[0]);
}
});
return dfd.promise();
}
// Similar code for transitDirections.
This results in a spaghetti of done
and Deferred
functions, which makes the code very hard to understand. Is there a proper way to solve this? E.g., could I re-program my Google Maps functions to make them synchrounous, or is there another (easier) way to only continue executing code when the previous function has returned a variable?