延迟与超时

sleep

返回一个在指定时间后解决的 Promise,用于 await 暂停执行。

ts
declare function sleep(time: number): Promise<unknown>
参数类型说明
timenumber延迟时间(毫秒)

示例

tsx
import { sleep } from 'vitarx'

async function loadData() {
  console.log('开始加载')
  await sleep(1000) // 等待 1 秒
  console.log('加载完成')
}

withDelayTimeout

为异步任务添加延迟回调和超时控制。返回一个带 cancel 方法的 Promise

ts
declare function withDelayTimeout<T>(
  task: Promise<T> | (() => Promise<T>),
  options: DelayTimeoutOptions<T>
): Promise<T> & { cancel: () => void }

参数

参数类型说明
taskPromise<T> | (() => Promise<T>)异步任务,可以是 Promise 或返回 Promise 的函数
optionsDelayTimeoutOptions<T>配置选项

DelayTimeoutOptions 选项

属性类型默认值说明
delaynumber0延迟触发回调的毫秒数(如显示 loading)
timeoutnumber0超时时间(毫秒),<=0 不生效
onDelay() => void延迟触发回调,一般用于显示加载状态
onTimeout(error: Error) => void超时回调
onResolve(value: T) => void任务成功时的回调
onReject(error: unknown) => void任务失败时的回调
isActive() => boolean判断任务是否仍然活跃,返回 false 则取消任务

示例

tsx
import { withDelayTimeout } from 'vitarx'

function App() {
  const loading = ref(false)
  const data = ref(null)

  async function fetchData() {
    loading.value = false

    const result = await withDelayTimeout(() => fetch('/api/data').then((res) => res.json()), {
      // 200ms 后还没返回数据就显示 loading
      delay: 200,
      onDelay: () => {
        loading.value = true
      },
      // 5 秒超时
      timeout: 5000,
      onTimeout: (err) => {
        console.error(err.message)
      },
      onResolve: (value) => {
        loading.value = false
        data.value = value
      },
      onReject: (err) => {
        loading.value = false
        console.error('请求失败', err)
      }
    })
  }

  return (
    <div>
      <button onClick={fetchData}>加载数据</button>
      {loading.value && <div>加载中...</div>}
      {data.value && <div>{JSON.stringify(data.value)}</div>}
    </div>
  )
}

手动取消任务:

tsx
import { withDelayTimeout } from 'vitarx'

const task = withDelayTimeout(fetch('/api/data'), {
  timeout: 5000,
  onTimeout: (err) => console.error(err.message)
})

// 需要时手动取消
task.cancel()

下一步