我正在努力寻找一种方法来获取两个api调用的“结果”,然后将它们一起处理。在两个调用中,我收到JSON,然后将其解析为GeoJSON格式。那么我希望能够将这两个geojson对象放入另一个函数中,所以假设它们必须变成“全局”?
我知道我在这里处理异步问题并且解决方案可能会在同一个函数中执行两个API调用吗?我无法理解如何做到这一点。
PS先前在页面中创建了一个传单地图,因此地图引用。
###First API Call
$.ajax({
url:"PORT API URL",
dataType: "json",
success: function(port_response){
port_callback(port_response)
}})
function port_callback(port_response) {
var port_geojson = {
type: "FeatureCollection",
features: [],
};
for (var i in port_response.data) {
port_geojson.features.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [port_response.data[i].longitude, port_response.data[i].latitude]
},
"properties": {
"stationName": port_response.data[i].port_name
}})}
L.geoJSON(port_geojson).addTo(map);
};
###Second API Call
$("#single-postcode").click(function (event) {
event.preventDefault();
var $result = $("#single-postcode-result").slideUp(),
postcode = $("#single-postcode-input").val();
$.get(encodeURI("POSTCODE API URL" + postcode))
.done(function (data) {
displayJsonResult($result, data);
callback1(data)
callback2(data)
})
.fail(function (error) {
displayJsonResult($result, error.responseJSON);
});
});
var displayJsonResult = function ($context, data) {
$context.html(JSON.stringify(data, null, 4)).slideDown();
console.log(JSON.stringify(data))
}
function callback1(data) {
var geojson = {
type: "FeatureCollection",
features: [],
};
for (var i in data.result) {
geojson.features.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [data.result.longitude, data.result.latitude]
},
"properties": {
"postcode": data.result.postcode
}
})};
L.geoJSON(geojson).addTo(map);
map.setView([JSON.parse(data.result.latitude),JSON.parse(data.result.longitude)], 14);
};
答案 0 :(得分:1)
我们可以使用ES6 Promise方法来实现这一点,这里有一个简单的例子来调用两个异步函数并返回一些字符串。
function firstFunction(duration) {
return new Promise(function(resolve, reject) {
//you can call your ajax call here and put your success response inside resolve callback
setTimeout(resolve("FirstObject"), duration);
});
}
function secondFunction(duration) {
return new Promise(function(resolve, reject) {
setTimeout(resolve("secondObject"), duration);
});
}
var promiseAll = firstFunction(5000).then(() => {
//promise all the method to get all result of all async calls
return Promise.all([firstFunction(100), secondFunction(200)]);
})
let result = document.getElementById("result");
promiseAll.then((val)=>{ result.InnerHtml = "First and second Fullfillment done.." + val;
console.log("First and second Fullfillment done.. "+val)},
(err)=>{console.log("one/all rejected "+err)})
<p>Once you run the function you can see the return values from each function call</p>
<div id="result">
</div>
答案 1 :(得分:0)
您可以尝试使用它。把两个api召集在一起!!当两个api都成功时它会执行
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
.then( myFunc, myFailure );