首先,你需要创建一个异步函数,该函数接受一个 IP 地址作为参数,然后使用 fetch 函数向 https://api.ip.sb/geoip 发送请求。然后,你需要处理返回的 Promise 对象,将其解析为 JSON 格式,然后返回国家信息。
然后,你需要遍历 IP 地址数组,对每个 IP 地址调用上述函数,然后打印出返回的国家信息。
这是一个示例代码:
const fetchCountryInfo = async (ip: string): Promise<string> => {
const response = await fetch(`https://api.ip.sb/geoip/${ip}`);
const data = await response.json();
return data.country;
}
const ipList = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4', '5.5.5.5'];
ipList.forEach(async ip => {
const country = await fetchCountryInfo(ip);
console.log(`Country for IP ${ip} is ${country}`);
});请注意,由于网络请求是异步的,所以打印的国家信息可能不会按照 IP 地址数组的顺序出现。如果你需要按照顺序打印国家信息,你可以使用 for...of 循环和 async/await,如下所示:
const fetchCountryInfo = async (ip: string): Promise<string> => {
const response = await fetch(`https://api.ip.sb/geoip/${ip}`);
const data = await response.json();
return data.country;
}
const ipList = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4', '5.5.5.5'];
(async () => {
for (const ip of ipList) {
const country = await fetchCountryInfo(ip);
console.log(`Country for IP ${ip} is ${country}`);
}
})();在这个版本的代码中,我们使用了一个立即执行的异步函数(IIFE),这样我们就可以在循环中使用 await 关键字,确保每次只有一个请求在执行,从而保证打印的国家信息按照 IP 地址数组的顺序出现。