Fetch設定タイムアウト時間
6466 ワード
/**
*
*
* @param {string} url
* @param {number}
* @returns
*/
function request(url,wait=30) {
return new Promise((resolve, reject) => {
let status = 0; // 0 1 2
let timer = setTimeout(() => {
if (status === 0) {
status = 2;
timer = null;
reject(" ");
}
}, 3000);
fetch(url, {
headers: {
"content-type": "application/json"
}
})
.then(res => res.json())
.then(res => {
if (status !== 2) {
clearTimeout(timer);
resolve(res);
timer = null;
status = 1;
}
});
});
}
request("/test")
.then(res => {
document.body.innerHTML =
typeof res !== "string" ? JSON.stringify(res) : res;
})
.catch(err => {
console.log("err", err);
});