我有以下对象,存储在变量 ( $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 是否有效/响应,
如果为 true,则$._findService()
创建一个仅包含键及其元素的新数组,
并且应该返回这个新数组。
不幸的是,我在第三步 - 返回新数组时遇到了问题。
我已经谷歌搜索并尽可能多地阅读关于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。
凤凰求蛊
绝地无双
相关分类