我有以下对象,存储在变量($gameSystem._ipLookupJSON
)中:
{
"www.geoplugin.net/json.gp?jsoncallback=?": {
"IP": "geoplugin_request",
"Country": "geoplugin_countryCode",
"City": "geoplugin_city"
},
"gd.geobytes.com/GetCityDetails?callback=?": {
"IP": "geobytesipaddress",
"Country": "geobytescountry",
"City": "geobytescity"
},
"ip-api.com/json": {
"IP": "ip",
"Country": "country_name",
"City": "city"
},
"ipinfo.io/json": {
"IP": "ip",
"Country": "country",
"City": "city"
}
}
此对象中的每个键都是一个 URL。
我有一个函数($._findService()
):
遍历这些键中的每一个并将它们发送到另一个函数(
$._urlExists()
),该函数检查 URL 是否有效/响应,如果为真,
$._findService()
则创建一个仅包含键及其元素的新数组,- 并且应该返回这个新数组。
不幸的是,我在第三步返回新数组时遇到了问题。
我已经在 Google 上搜索并尽可能多地阅读了Promises、.then和Async/Await,但我就是想不通,只是盯着这些代码行我就束手无策了。
const isServiceAvailable = async url_to_check => {
console.log(url_to_check);
return await subaybay.an._urlExists("http://" + url_to_check);
};
const checkServices = async(json_data) => {
return await Promise.all(Object.keys(json_data).map(url_to_check => isServiceAvailable(url_to_check)));
};
$._findService = function(json_data) {
var url_check = checkServices(json_data);
url_check.then(function(values) {
for (i = 0; i < values.length; i++) {
if (values[i] === true) {
var service_to_use = new Promise(function(resolve, reject) {
var result = [];
result.push(json_data[Object.keys(json_data)[i]]);
result.unshift(Object.keys(json_data)[i]);
resolve(result);
});
service_to_use.then(function(value) {
console.log(value);
return value;
});
};
};
});
};
我希望$._findService()
返回一个数组。
但可惜我得到的是undefined
。
如果我的代码不优雅或不漂亮,我深表歉意——我从 2 月底开始一直在自学 JavaScript。