调用这些多个getJSON API调用的正确方法是什么?

时间:2018-04-06 16:17:59

标签: javascript jquery

正如你在下面看到的那样,我将它们嵌套,每个都取决于前一个的结果。我认为将它们链接在一起会更好(只需将它们连续排列)但是每个结果需要一段时间才能返回并且它是异步的。当我调用该函数时,结果尚未加载,并返回undefined。在尝试获得结果之前,如何确保在函数中完成所有操作?

<!DOCTYPE html>
<head>

</head>

<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">

/* 
To get endpoint
https://api.weather.gov/points/39.7456,-97.0892

To get office, zone, forecast etc from end point
https://api.weather.gov/gridpoints/TOP/31,80
*/

var tLat = 40.985;
var tLon = -71.696;

stationString = getStationFromLatLon(tLat,tLon);
console.log(stationString);



function getStationFromLatLon(theLat,theLon){

    theURL = 'https://api.weather.gov/points/' + theLat + "," + theLon;
    var obsStationsURL;
    var obsStationURL;

    // This passes in the lat lons and gets the weather observation stations 
    $.getJSON(theURL, function(data){
        console.log(data);

        obsStationsURL = data.properties.observationStations;

        console.log(obsStationsURL);

        // Get the first obsStation using the obsStations URL
        $.getJSON(obsStationsURL, function(data2){

            obsStationURL = data2.observationStations[0];

            console.log(obsStationURL);

            // Get the weather station ID and name using the station URL from previous call
            $.getJSON(obsStationURL, function(data3){
                stationID = data3.properties.stationIdentifier;
                stationName = data3.properties.name;

                console.log(stationID + " " + stationName);
                returnString = stationID + " " + stationName;
                return returnString; 
            })

        });
    });
}


</script>
</body>

2 个答案:

答案 0 :(得分:-1)

您需要返回Promise并等待响应。试试这个:

&#13;
&#13;
var tLat = 40.985;
var tLon = -71.696;

function getStationFromLatLon(theLat, theLon) {
  return new Promise((resolve, reject) => {
    var theURL = "https://api.weather.gov/points/" + theLat + "," + theLon;
    var obsStationsURL;
    var obsStationURL;
    // This passes in the lat lons and gets the weather observation stations
    $.getJSON(theURL, function(data) {
      console.log(data);
      obsStationsURL = data.properties.observationStations;
      console.log(obsStationsURL);
      // Get the first obsStation using the obsStations URL
      $.getJSON(obsStationsURL, function(data2) {
        obsStationURL = data2.observationStations[0];
        console.log(obsStationURL);
        // Get the weather station ID and name using the station URL from previous call
        $.getJSON(obsStationURL, function(data3) {
          var stationID = data3.properties.stationIdentifier;
          var stationName = data3.properties.name;
          console.log(stationID + " " + stationName);
          var returnString = stationID + " " + stationName;
          resolve(returnString);
        });
      });
    });
  });
}

getStationFromLatLon(tLat, tLon).then(stationString => {
  console.log(stationString);
});
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

使用then返回的Promise的$.getJSON方法可以简化一点:

const getStationFromLatLon = (lat, lng) => 
  $.getJSON('https://api.weather.gov/points/' + lat + "," + lng)
  .then(data => $.getJSON(data.properties.observationStations))
  .then(data => $.getJSON(data.observationStations[0]))
  .then(data => `${data.properties.name} ${data.properties.stationIdentifier}`)

getStationFromLatLon(39.7456, -97.0892)
  .then(console.log)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

您还可以使用符合标准的fetch代替jQuery的Ajax,使用这个简单的包装器:

const getJson = (url) => fetch(url).then(resp => resp.json());

这没有错误检查,但原件也没有。为了更清洁,您需要检查您要搜索的属性是否包含在返回的数据中。