javascript - 处理两个单独的 JQuery Api 调用

标签 javascript jquery json geojson

我正在努力寻找一种方法来获取两个 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/

相关文章:

javascript - 具有多个条件的过滤器数组

javascript - 我无法让光谱颜色选择器工作。我缺少什么?

javascript - 使用Jquery拖放,从拖放的div中获取值

jQuery - 通过容器 ID 获取表单元素

javascript - Nodejs 返回 Blockchain Rates API 的完整 JSON,但我无法访问其中的特定对象。为什么?

json - Swift 3 - 提取 JSON 数据

javascript - 判断一个多词字符串是否包含一个词

php - JQuery 使用 THIS 作为 .on [选择器]

c# - 如何设置 JSON 对象从结果开始?.Net MySQL JSON Restful Webservice?

javascript - 将不同大小的圆圈打包成矩形 - d3.js