How to call $.getJSON() in a for loop?
I am coming from the synchronous world and I have not grasped the concept of closures yet. I am trying to loop through an array of airport ids calling the
getJSON
method and build a new array with data from the returned json data for each airport.
Could someone please look at the code below and explain how to make it work? Thanks in advance!
- var airportswx = [];
- for (key in airports) {
- obj = airports[key];
- xdata = getwx(obj.apt);
- airportswx.push({ 'apt': obj.apt, 'name': xdata.name, 'wx': xdata.delay } )
- }
- function getwx(apt) {
- var url = 'http://services.faa.gov/airport/status/' + apt + '? format=application/json&callback=?'
- console.log(url);
- $.getJSON(url, function (data) {
- return(data);
- });
- }