async-poll
Advanced polling module with timeout and metrics collection
Writing your own polling function can be difficult and hard to collect metrics about the polling.
asyncPoll
aims to solve those with modern JavaScript and advanced API. By leveragingasync...await
, asynchronous polling function has never been easier and Performance Timing/ Timeline API is used to collect metrics about each polling in terms of the duration.🛠 Please check if
Performance Timing/ Timeline API
is supported on your browser or Node.js environment.
Table of contents
Pre-requisites
Install
# Install via NPM $ npm install --save async-poll
Usage
TypeScript or native ES modules
; /** Fetch news from a mock URL */;/** Keep polling until the more than 100 `news` are received or `status` returns `complete` */;/** Poll every 2 seconds */;/** Timeout after 30 seconds and returns end result */; asyncPollfn, conditionFn, .thenconsole.log .catchconsole.error;
Node.js
const asyncPoll = ; /** Fetch news from a mock URL */const fn = async ;/** Keep polling until the more than 100 `news` are received or `status` returns `complete` */const conditionFn = ddatanewslength > 100 || ddatastatus === 'complete';/** Poll every 2 seconds */const interval = 2e3;/** Timeout after 30 seconds and returns end result */const timeout = 30e3; ;
Browser
ES Modules
IIFE
PerformanceObserver
Performance Timing/ Timeline API via Performance timing data can be obtained via the experimental Performance Tming API that has been added as of Node.js 8.5.0 or Performance Timeline API on browsers.
/** For Node.js **only**, no import is required on browser. */;
API Reference
AsyncPollOptions
asyncPoll<T>(fn, conditionFn[, options])
fn
<Function> Function to execute for each polling happens.conditionFn
<Function> Function to check the condition before a subsequent polling takes place. The function should return a boolean. Iftrue
, the polling stops and returns with a value in the type ofT
.options
<AsyncPollOptions> Polling options.- returns: <Promise<
T
>> Promise which resolves with a value in the type ofT
.
License
MIT License © Rong Sen Ng (motss)