我制作了一个应用程序,可以提取其他网站的一些数据。
每个站点都有一个特定的 Parser
。
现在有时这些网站将来会停止工作或可能出现问题。
我希望能够检查这些网站中的每一个,看看它是否在线。
这个检查会在应用启动时触发,所以我希望它快。
我想出了一个简单的方法来做到这一点,但我想知道是否还有更好的方法来做到这一点。
这是我目前的做法。
static async fetchWithTimeout(url: string, options) {
const {
timeout = 8000
} = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(url, {
...options,
signal: controller.signal
});
clearTimeout(id);
return response;
}
static async isOnline(url: string) {
try {
console.log(`Sending isOnline request to ${url}`);
let headers = new Headers({
Accept: '*/*',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
});
var data = await httpClient.fetchWithTimeout(url, {
timeout: 10000,
headers: headers,
method: 'GET'
})
return data.ok;
} catch (error) {
return false;
}
}
然后简单调用 await httpClient.isOnline("www.google.se");
你认为最快的方法是什么
答案 0 :(得分:1)
您当前编写代码的方式告诉我,您需要等待每个网站的超时检查结果。 IE。如果您有 5 个网站并且您的超时设置为 10 秒,您的应用将在启动前等待 50 秒。
我认为有一种更有效的方法。您应该让 fetchWithTimeout
函数返回带有检查结果的承诺。然后,您可以同时对所有 5 个站点进行超时检查,并将它们的承诺收集到一个数组中,然后可以使用 Promise.all
解决该问题。这是总体思路:
const fetchWithTimeout = (url, options) => {
const { timeout = 8000 } = options;
return new Promise((resolve) => {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
fetch(url, {
...options,
signal: controller.signal
})
.then((r) => {
if (r.ok) {
resolve({ url, msg: "ok" });
} else {
resolve({ url, msg: "error" });
}
})
.catch((e) => resolve({ url, msg: "error" }));
clearTimeout(id);
});
};
const sites = ["https://4.2.2.2", "https://httpstat.us/200", "https://httpstat.us/404"];
Promise.all(sites.map((url) => fetchWithTimeout(url, { timeout: 10000 })))
.then((result) => {
const good_sites = result.filter((site) => site.msg === "ok");
const down_sites = result.filter((site) => site.msg === "error");
console.log("Good sites:", good_sites);
console.log("Down sites:", down_sites);
});
在三个网站 ["https://4.2.2.2", "https://httpstat.us/200", "https://httpstat.us/404"]
中,只有 google.com 会“上线”。第一个会超时,最后一个会返回 404。但最重要的是你可以在 10 秒内检查它们。