【问题标题】:How to return multiple values from an Ajax request that is called in a promise chain如何从承诺链中调用的 Ajax 请求返回多个值
【发布时间】:2020-09-16 09:48:58
【问题描述】:

我一直在使用 Promise 调用异步 AJAX 请求函数,这些函数为我的地理定位应用返回 API JSON 对象。我已经成功地使用 then() 函数链接并返回每个 Promise 的数据并相应地使用它。

我想使用的最后一个 Promise 不调用 API,它是一个包含地理数据的文件。我返回这些数据没有问题,但我需要做的是从最后一个 then() 链返回数据和一个附加变量。这是最后一段代码和AJAX函数。

// ---- Following previous promise chain ---- //

return openWeather

}).then(function(data4) {

            console.log(data4)

            // Disregard this code

            $('#txtDescription').html(data4['data'][0]['weather']['description']);
            $('#txtSpeed').html(data4['data'][0]['wind_spd'] + ' mph');
            $('#txtDirection').html(data4['data'][0]['wind_dir'] + ' °');
            $('#txtTemp').html(data4['data'][0]['temp'] + ' ° celcius');

            // I need to return this variable

            let iso2 = data4['data'][0]['country_code'];

            // I also need to return this function

            return geoData(iso2);

        }).then(function(result) {

            // I am trying to assigin two values from a returned array     

            let iso2 = result[0]
            let data5 = result[1]

            // Both console.logs read as undefined.

            console.log(iso2)
            console.log(data5);

我在另一个文件中有我的 AJAX 调用,我将它们作为模块导入。

function geoData(iso2) {
    return $.ajax({
        type: "GET",
        url: "countries.geo.json",
        dataType: 'json',
        success: function (data5) {
            
            // both the variables log to the console here so I know they are being sent to the success function
            console.log(iso2)
            console.log (data5)

            // The only way I can think to return both values is to return an array.
            
            return [ iso2, data5 ]
        }
    });
};

我可以从“geoData()”AJAX 调用或“iso2”变量中返回数据,但不能同时返回。我基本上需要在条件/循环中使用该变量,该变量将与返回的 JSON 对象进行比较并将其与特定国家/地区匹配。

是否可以返回两个值而不是一个?非常感谢您的帮助。

【问题讨论】:

    标签: javascript ajax api asynchronous promise


    【解决方案1】:

    这不是您从 ajax 调用返回数据的方式。不是从 ajax 调用返回 2 个值,而是从调用中返回一个值,但从函数中返回 2 个值,如下所示:

    function geoData(iso2) {
      return $.ajax({
        type: "GET",
        url: "https://jsonplaceholder.typicode.com/posts/1",
        dataType: 'json'
      }).then(data => [iso2, data]);
    };
    
    geoData("test").then(result => {
      console.log("result[0]", result[0]);
      console.log("result[1]", result[1]);
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-10
      • 2017-02-22
      • 2014-10-31
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 2017-05-15
      • 2019-01-13
      相关资源
      最近更新 更多