UNPKG

pr-fetch

Version:

基于fetch额外封装了检查请求、中止请求。

52 lines (51 loc) 1.27 kB
class c { #s = { timeout: 5 * 1e3, check: !1 }; #t; constructor(t = {}) { this.#s = { ...this.#s, ...t }; } /** * * @param input string | URL | Request * @param init RequestInit */ check = (t, o) => new Promise(async (a, s) => { this.stop(), this.#t = new AbortController(); const e = window.setTimeout(() => { this.#t?.abort("Timeout."), s({ status: "timeout", reason: "" }); }, this.#s.timeout); try { const r = await fetch(t, { ...o, method: "HEAD", signal: this.#t?.signal }); r.status === 200 ? a({ status: "successed", reason: "" }) : s({ status: "failed", reason: `${r.status}` }); } catch (r) { s({ status: "error", reason: r.message }); } clearTimeout(e); }); /** * * @param input string | URL | Request * @param init RequestInit */ request = async (t, o) => new Promise(async (a, s) => { try { this.#s.check && await this.check(t, o), this.#t = new AbortController(); const e = await fetch(t, { ...o, signal: this.#t?.signal }); a(e); } catch (e) { this.stop(), s(e); } }); /** * stop */ stop = () => { this.#t?.signal.aborted === !1 && this.#t.abort("Actively stop."); }; } export { c as PrFetch };