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() { async function main() {
fetchAsync("https://api.ip.sb/geoip").then( try {
function (value) { const [geoIP, speedTest, ipApiIs] = await Promise.all([
v = value; fetchAsync("https://api.ip.sb/geoip"),
document.getElementById("check-ipsb-ip").innerHTML = v.ip; fetchAsync("https://api-v3.speedtest.cn/ip"),
document.getElementById("check-ipsb-location").innerHTML = [ fetchAsync("https://api.ipapi.is/"),
v.city, ]);
v.country,
v.isp, // Update DOM for IP.sb
].join(", "); updateDom("check-ipsb-ip", geoIP.ip);
}, updateDom("check-ipsb-location", [geoIP.city, geoIP.country, geoIP.isp]);
function (error) {
console.log(error); // Update DOM for SpeedTest.cn
}, const { ip, city, country, isp } = speedTest.data;
); updateDom("check-speedtestcn-ip", ip);
fetchAsync("https://api-v3.speedtest.cn/ip").then( updateDom("check-speedtestcn-location", [city, country, isp]);
function (value) {
v = value.data; // Update DOM for IPAPI.is
document.getElementById("check-speedtestcn-ip").innerHTML = v.ip; const {
document.getElementById("check-speedtestcn-location").innerHTML = [ ip: ipapiIP,
v.city, location: { city: ipapiCity, country: ipapiCountry },
v.country, company: { name: companyName },
v.isp, } = ipApiIs;
].join(", "); updateDom("check-ipapiis-ip", ipapiIP);
}, updateDom("check-ipapiis-location", [ipapiCity, ipapiCountry, companyName]);
function (error) { } catch (error) {
console.log(error); console.log("Error fetching data:", 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 fetchAsync(url) { async function fetchAsync(url) {
let response = await fetch(url); try {
let data = await response.json(); const response = await fetch(url);
return data; 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 () { function updateDom(elementId, content) {
main(); document.getElementById(elementId).innerHTML = Array.isArray(content)
}; ? content.join(", ")
: content;
}
window.onload = main;