Skip to content

poll

Static Badge

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

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

Arguments

ArgTypeOptionalDefaultDescription
func(...args: any[]) => Promise<T>falseundefinedポーリング対象の非同期関数
waitnumberfalseundefinedポーリング間隔(ミリ秒)
optionsPollOptions<T>trueundefinedポーリング設定
options.maxRetriesnumbertrue3失敗時の最大リトライ回数。成功時にカウンターをリセット
options.maxCallsnumbertrueInfinityMaximum number of calls of func
options.sequentialbooleantruefalse前回の実行が完了するまで次回を待機
options.leadingbooleantruetrue直ちに 1 回実行
options.onSuccess(result: T, retries: number) => voidtrueundefined成功時のコールバック
options.onFailure(error: any, retries: number) => voidtrueundefined失敗時のコールバック

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
}