poll
Provide a function func
that returns a Promise
and a wait interval wait
, and return a function that polls the asynchronous task at a fixed interval, supporting configurable retries and runtime control.
Optional parameter options configures retry behavior; see here.
The function returns an object to control polling; see here.
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 |
| Type of the value returned by the Promise of function func |
Arguments
Arg | Type | Optional | Default | Description |
---|---|---|---|---|
func | (...args: any[]) => Promise<T> | false | undefined | The async function to poll |
wait | number | false | undefined | Interval in milliseconds between polls |
options | PollOptions<T> | true | undefined | Polling configuration |
options.maxRetries | number | true | 3 | Max retry count on failure; Reset counter on success |
options.maxCalls | number | true | Infinity | Maximum number of calls of func |
options.sequential | boolean | true | false | Wait for previous run before next poll |
options.leading | boolean | true | true | Execute once immediately |
options.onSuccess | (result: T, retries: number) => void | true | undefined | Callback on success |
options.onFailure | (error: any, retries: number) => void | true | undefined | Callback on failure |
Returns
Type |
---|
(...args: Parameters<typeof func>) => PollResult |
PollOptions
The type of options
parameter of the poll
function.
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
The return of the poll
function.
Added in v0.0.4
Source
ts
export interface PollResult {
stop: () => void
start: () => void
isRunning: () => boolean
}