refactor(js): simplify

This commit is contained in:
Guanran Wang 2024-10-19 12:11:20 +08:00
parent ea36c48f40
commit 49ca0945fb
Signed by: nyancat
GPG key ID: 91F97D9ED12639CF

View file

@ -1,54 +1,50 @@
function main() {
fetchAsync("https://api.ip.sb/geoip").then(
function (value) {
v = value;
document.getElementById("check-ipsb-ip").innerHTML = v.ip;
document.getElementById("check-ipsb-location").innerHTML = [
v.city,
v.country,
v.isp,
].join(", ");
},
function (error) {
console.log(error);
},
);
fetchAsync("https://api-v3.speedtest.cn/ip").then(
function (value) {
v = value.data;
document.getElementById("check-speedtestcn-ip").innerHTML = v.ip;
document.getElementById("check-speedtestcn-location").innerHTML = [
v.city,
v.country,
v.isp,
].join(", ");
},
function (error) {
console.log(error);
},
);
fetchAsync("https://api.ipapi.is/").then(
function (value) {
v = value;
document.getElementById("check-ipapiis-ip").innerHTML = v.ip;
document.getElementById("check-ipapiis-location").innerHTML = [
v.location.city,
v.location.country,
v.company.name,
].join(", ");
},
function (error) {
console.log(error);
},
);
async function main() {
try {
const [geoIP, speedTest, ipApiIs] = await Promise.all([
fetchAsync("https://api.ip.sb/geoip"),
fetchAsync("https://api-v3.speedtest.cn/ip"),
fetchAsync("https://api.ipapi.is/"),
]);
// Update DOM for IP.sb
updateDom("check-ipsb-ip", geoIP.ip);
updateDom("check-ipsb-location", [geoIP.city, geoIP.country, geoIP.isp]);
// Update DOM for SpeedTest.cn
const { ip, city, country, isp } = speedTest.data;
updateDom("check-speedtestcn-ip", ip);
updateDom("check-speedtestcn-location", [city, country, isp]);
// Update DOM for IPAPI.is
const {
ip: ipapiIP,
location: { city: ipapiCity, country: ipapiCountry },
company: { name: companyName },
} = ipApiIs;
updateDom("check-ipapiis-ip", ipapiIP);
updateDom("check-ipapiis-location", [ipapiCity, ipapiCountry, companyName]);
} catch (error) {
console.log("Error fetching data:", error);
}
}
async function fetchAsync(url) {
let response = await fetch(url);
let data = await response.json();
return data;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.log("Fetch error:", error);
throw error;
}
}
window.onload = function () {
main();
};
function updateDom(elementId, content) {
document.getElementById(elementId).innerHTML = Array.isArray(content)
? content.join(", ")
: content;
}
window.onload = main;