我正在努力寻找一种方法来获取两个 api 调用的“结果”,然后一起处理它们。在这两个调用中,我都收到 JSON,然后将其解析为 GeoJSON 格式。然后,我希望能够将这两个 geojson 对象放入另一个函数中,因此假设它们必须变为“全局”?
我知道我在这里处理异步问题,解决方案可能是在同一个函数中执行两个 API 调用?我不知道该怎么做。
PS 页面前面有一张传单 map ,因此有 map 引用。
###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);
};
最佳答案
我们可以使用 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>
关于javascript - 处理两个单独的 JQuery Api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747049/