poll
传入返回 Promise
的函数 func
和等待间隔 wait
,返回一个函数,它以固定间隔轮询异步任务,支持可配置的重试和运行时控制。
可选参数 options
设置重试的配置,具体看这里。
函数返回一个控制轮询的对象,具体看这里。
Added in v0.0.4
Usage
ts
import { poll } from 'parsnip-kit'
const getList = () => {
return fetch('https://example.url.test/list').then((response) => {
response.json()
// ...
})
}
const polled = poll(getList, 1000)
const pollResult = polled()
// ...
// Stop polling
pollResult.stop()
API
Type Parameter
Arg | Type | Description |
---|---|---|
T |
| 函数 func 返回的 Promise 的value 类型 |
Arguments
Arg | Type | Optional | Default | Description |
---|---|---|---|---|
func | (...args: any[]) => Promise<T> | false | undefined | 要轮询的异步函数 |
wait | number | false | undefined | 轮询间隔(毫秒) |
options | PollOptions<T> | true | undefined | 轮询配置 |
options.maxRetries | number | true | 3 | 失败时最大重试次数,轮询成功时内部重试次数计数就会被重置 |
options.maxCalls | number | true | Infinity | Maximum number of calls of func |
options.sequential | boolean | true | false | 等待上一次执行完成后再开始下一次轮询 |
options.leading | boolean | true | true | 立即执行一次 |
options.onSuccess | (result: T, retries: number) => void | true | undefined | 成功时的回调 |
options.onFailure | (error: any, retries: number) => void | true | undefined | 失败时的回调 |
Returns
Type |
---|
(...args: Parameters<typeof func>) => PollResult |
PollOptions
poll
函数的参数 options
的类型。
Added in v0.0.4
Source
ts
export interface PollOptions<T> {
maxRetries?: number
sequential?: boolean
leading?: boolean
maxCalls?: number
onSuccess?: (result: T, retries: number) => void
onFailure?: (error: any, retries: number) => void
}
PollResult
poll
函数的返回值类型。
Added in v0.0.4
Source
ts
export interface PollResult {
stop: () => void
start: () => void
isRunning: () => boolean
}