默认情况下,fetch没有cookie错误,不会拒绝HTTP错误(例如404PageNotFound或500InternalServerError),不会导致Fetch返回的Promise被标记为reject;.catch()不会被执行。如果想准确判断fetch是否成功,需要包含resolved的promise,然后判断response.ok是否为true//不支持直接设置timeout,可以使用promisefunctionfetchTimeout(url,init,timeout=3000){returnnewPromise((resolve,reject)=>{fetch(url,init).then(resolve).catch(reject);setTimeout(reject,timeout);})}//Abortfetchconstcontroller=newAbortController();fetch('http://domain/service',{method:'GET',signal:controller.signal}).then(response=>response.json()).then(json=>console.log(json)).catch(error=>console.error('Error:',error));controller.abort();interfaceIOptions{url:string;类型?:字符串;数据:任何;timeout?:number;}functionformatUrl(json){让dataArr=[];json.t=Math.random();for(letkeyinjson){dataArr.push(`${key}=${encodeURIComponent(json[key])}`)}returndataArr.join('&');}exportfunctionajax(options:IOptions){returnnewPromise((resolve,reject)=>{if(!options.url)return;options.type=options.type||'GET';options.data=options.data||{};options.timeout=options.timeout||10000;letdataToUrlstr=formatUrl(options.data);lettimer;//1.创建letxhr;if((windowasany).XMLHttpRequest){xhr=newXMLHttpRequest();}else{xhr=newActiveXObject('Microsoft.XMLHTTP');}if(options.type.toUpperCase()==='GET'){//2.连接xhr.open('get',`${options.url}?${dataToUrlstr}`,true);//3.发送xhr.send();}elseif(options.type.toUpperCase()==='POST'){//2.连接xhr.open('post',options.url,true);xhr.setRequestHeader('ContentType','application/x-www-form-urlencoded');//3.发送xhr.send(options.data);}//4.接收xhr.onreadystatechange=()=>{if(xhr.readyState===4){clearTimeout(timer);如果(xhr.status>=200&&xhr.status<300||xhr.status===304){resolve(xhr.responseText);}else{拒绝(xhr.status);}}}if(options.timeout){timer=setTimeout(()=>{xhr.abort();reject('超时');},options.timeout)}//xhr.timeout=options.timeout;//xhr.ontimeout=()=>{//reject('超时');//}});}
