Skip to content

poll

Static Badge

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

ArgTypeDescription
TType of the value returned by the Promise of function func

Arguments

ArgTypeOptionalDefaultDescription
func(...args: any[]) => Promise<T>falseundefinedThe async function to poll
waitnumberfalseundefinedInterval in milliseconds between polls
optionsPollOptions<T>trueundefinedPolling configuration
options.maxRetriesnumbertrue3Max retry count on failure; Reset counter on success
options.maxCallsnumbertrueInfinityMaximum number of calls of func
options.sequentialbooleantruefalseWait for previous run before next poll
options.leadingbooleantruetrueExecute once immediately
options.onSuccess(result: T, retries: number) => voidtrueundefinedCallback on success
options.onFailure(error: any, retries: number) => voidtrueundefinedCallback 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
}