pr-fetch
Version:
基于fetch额外封装了检查请求、中止请求。
2 lines (1 loc) • 1.07 kB
JavaScript
(function(t,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(t=typeof globalThis<"u"?globalThis:t||self,s(t["pr-fetch"]={}))})(this,(function(t){"use strict";class s{#e={timeout:5*1e3,check:!1};#t;constructor(e={}){this.#e={...this.#e,...e}}check=(e,r)=>new Promise(async(a,o)=>{this.stop(),this.#t=new AbortController;const i=window.setTimeout(()=>{this.#t?.abort("Timeout."),o({status:"timeout",reason:""})},this.#e.timeout);try{const n=await fetch(e,{...r,method:"HEAD",signal:this.#t?.signal});n.status===200?a({status:"successed",reason:""}):o({status:"failed",reason:`${n.status}`})}catch(n){o({status:"error",reason:n.message})}clearTimeout(i)});request=async(e,r)=>new Promise(async(a,o)=>{try{this.#e.check&&await this.check(e,r),this.#t=new AbortController;const i=await fetch(e,{...r,signal:this.#t?.signal});a(i)}catch(i){this.stop(),o(i)}});stop=()=>{this.#t?.signal.aborted===!1&&this.#t.abort("Actively stop.")}}t.PrFetch=s,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})}));