timeout
为Promise添加超时限制
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.setTimeout | typeof setTimeout | 超时设置函数 |
deps.clearTimeout | typeof clearTimeout | 清除超时函数 |
函数签名
typescript
interface TimeoutDeps {
setTimeout: typeof setTimeout
clearTimeout: typeof clearTimeout
}
function timeout<T>(
promise: Promise<T>,
ms: number,
deps: TimeoutDeps
): Promise<T>参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
promise | Promise<T> | 是 | 原始Promise |
ms | number | 是 | 超时毫秒数 |
deps | TimeoutDeps | 是 | 环境依赖 |
返回值
| 类型 | 说明 |
|---|---|
Promise<T> | 带超时的Promise |
使用示例
typescript
// 限制请求超时时间为5秒
const data = await timeout(
fetch('/api/data'),
5000,
{ setTimeout, clearTimeout }
)
// 捕获超时错误
try {
await timeout(
longRunningTask(),
3000,
{ setTimeout, clearTimeout }
)
} catch (error) {
console.error('操作超时')
}