Skip to content

@pmun/utils / timeout

Function: timeout()

ts
function timeout<T>(
   promise, 
   ms, 
message?): Promise<T>;

带超时控制的 Promise

如果 Promise 在指定时间内没有完成,则拒绝并抛出超时错误。

Type Parameters

T

T

Parameters

promise

Promise<T>

要执行的 Promise

ms

number

超时时间(毫秒)

message?

string = 'Operation timed out'

超时错误信息,默认为 "Operation timed out"

Returns

Promise<T>

返回原 Promise 的结果,或在超时时抛出错误

Example

ts
// 正常完成
await timeout(fetch('/api/data'), 5000)

// 超时
try {
  await timeout(delay(3000), 1000)
} catch (error) {
  console.error('超时了')
}

// 自定义错误信息
await timeout(fetch('/api/data'), 5000, '请求超时')