繁体   English   中英

如何从承诺链中调用的 Ajax 请求中返回多个值

[英]How to return multiple values from an Ajax request that is called in a promise chain

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

我想使用的最后一个 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 对象进行比较并将其与特定国家/地区匹配。

是否可以返回两个值而不是一个? 我真的很感激你的帮助。

这不是您从 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM