Open lstoryc opened 4 years ago
var xhr = new XMLHttpRequest(); xhr.open("GET", "/server", true); xhr.timeout = 2000; xhr.onload = function () { console.warn("请求完成"); }; xhr.ontimeout = function (e) { console.error("超时啦"); }; xhr.send(null);
const fetch2 = (url, fetchParams = {}, delay = 6000) => { const abortController = new AbortController(); const signal = abortController.signal; const options = { ...fetchParams, signal }; console.warn("delay: ", delay); return Promise.race([ fetch(url, options), new Promise((res, rej) => { setTimeout(()=>{ console.warn('-----',delay); abortController.abort(); rej("Timeout"); }, delay); }), ]); }; fetch2("/a/1190000021322450",{}, 0).catch((e) => console.warn(e));
1. 基于XMLHTTPRequest
2. 基于Promise和Fetch