【发布时间】: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