处理可能超时的异步操作
SegmentFault
共 4203字,需浏览 9分钟
·
2021-11-20 09:44
作者:边城
简介:从事软件开发 20 年,在软件分析、设计、架构、开发及软件开发技术研究和培训等方面有着非常丰富的经验,近年主要在研究 Web 前端技术、基于 .NET 的后端开发技术和相关软件架构。
来源:SegmentFault 思否社区
Axios 自带超时处理
try {
const res = await axios.get(url, options);
// TODO 正常进行后续业务
} catch(err) {
// TODO 进行容错处理,或者报错
}
try {
showLoading();
const res = await axios.get(url, options);
// TODO 正常业务
} catch (err) {
// TODO 容错处理
} finally {
hideLoading();
}
try {...}
catch (err) {
if (err.isAxiosError && !err.response && err.request
&& err.message.startsWith("timeout")) {
// 如果是 Axios 的 request 错误,并且消息是延时消息
// TODO 处理超时
}
}
finally {...}
处理 fetch() 超时
const ac = new AbortController();
const { signal } = ac;
fetch(url, { signal }).then(res => {
// TODO 处理业务
});
// 1 秒后取消 fetch 操作
setTimeout(() => ac.abort(), 1000);
const ac = new AbortController();
const { signal } = ac;
setTimeout(() => ac.abort(), 1000);
const res = await fetch(url, { signal }).catch(() => undefined);
async function fetchWithTimeout(timeout, resoure, init = {}) {
const ac = new AbortController();
const signal = ac.signal;
setTimeout(() => ac.abort(), timeout);
return fetch(resoure, { ...init, signal });
}
setTimeout(() => {
console.log("It's timeout");
ac.abort();
}, timeout);
fetchWithTimeout(5000, url).then(res => console.log("success"));
async function fetchWithTimeout(timeout, resoure, init = {}) {
const ac = new AbortController();
const signal = ac.signal;
const timer = setTimeout(() => {
console.log("It's timeout");
return ac.abort();
}, timeout);
try {
return await fetch(resoure, { ...init, signal });
} finally {
clearTimeout(timer);
}
}
万物皆可超时
function waitWithTimeout(promise, timeout, timeoutMessage = "timeout") {
let timer;
const timeoutPromise = new Promise((_, reject) => {
timer = setTimeout(() => reject(timeoutMessage), timeout);
});
return Promise.race([timeoutPromise, promise])
.finally(() => clearTimeout(timer)); // 别忘了清 timer
}
(async () => {
const business = new Promise(resolve => setTimeout(resolve, 1000 * 10));
try {
await waitWithTimeout(business, 1000);
console.log("[Success]");
} catch (err) {
console.log("[Error]", err); // [Error] timeout
}
})();
- END -
评论