FCC's Weather App Project Part Two: Bittersweet Callbacks

Upon gathering my data from Weather Underground, I had written a simple script calling each piece of data thinking that is all I would need. I was wrong, however, and the reason is due to JavaScript's advantage as well as its disadvantage as a programming language.

JavaScript executes programs in an asynchronous fashion, which is unusual to a Ruby programmer like me. What's the difference? A synchronous program is executed line by line and whenever a defined function is called, the computer waits until the function has completed its work to move execute the remaining code. Asynchronous languages execute code whether or not a function has completed its work or not. This is a little confusing, but it is one the main reasons JavaScript is so popular: its quick. So why would this cause programming problems?

If I were to simply assign the "$.getJSON" call to a variable and log it to the console, it would return the JSON history, but not be accessible. Due to the asynchronous nature of JavaScript, the function executes after the JSON data is no longer available. However, JavaScript has a unique property that is both unusual, but also extremely useful: passing functions into functions. In order to retain the data from the API call we have to assign the data to a function and app it into other functions that use the data for our purposes. Imagine if you will that you have predefined functions and you’re essentially calling back to them throughout your script. This is called a callback and it is quite confusing but also quick. Here’s an idea of what a callback looks like in my script:

function testIdea(value){
console.log(value);
var apiCall = "https://api.wunderground.com/api/f946ee8192f9f7ca/conditions/q/" + value.location.state + "/" + value.location.city + ".json";
callData(apiCall);
}


var geoLocate = $.getJSON("https://api.wunderground.com/api/f946ee8192f9f7ca/geolookup/q/autoip.json", function(api) {

testIdea(api);

})

This tends to be very confusing, but not too bad once you get the hang of it. However, this outlines one of the disadvantages JavaScript has for large scale apps versus another backend language like Java. Imagine having different sets of callbacks for multiple types of information. The script will get quite confusing. However, now my scripts are set up and all I have to do it make my site pretty and add some minor functionality. The hard work is over and its nothing but sunny skies ahead!

No comments:

Post a Comment