🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more

async-poll

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

async-poll

Advanced polling module with timeout and metrics collection

1.4.0
latest
Version published
Weekly downloads
48
-46.67%
Maintainers
1
Weekly downloads
 
Created

async-poll

Advanced polling module with timeout and metrics collection

Buy Me A Coffee tippin.me Follow me

Version Node version MIT License

Downloads Total downloads Packagephobia Bundlephobia

CircleCI Dependency Status codecov Coverage Status

codebeat badge Codacy Badge Code of Conduct

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 leveraging async...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

interface NewsData {
  data: {
    news: object[];
    status: number;
  };
}

import asyncPoll from 'async-poll';

/** Fetch news from a mock URL */
const fn = async () => fetch('https://example.com/api/news').then(r => r.json());
/** Keep polling until the more than 100 `news` are received or `status` returns `complete` */
const conditionFn = (d: NewsData) => d.data.news.length > 100 || d.data.status === 'complete';
/** Poll every 2 seconds */
const interval = 2e3;
/** Timeout after 30 seconds and returns end result */
const timeout = 30e3;

asyncPoll<NewsData>(fn, conditionFn, { interval, timeout })
  .then(console.log)
  .catch(console.error);

Node.js

const { asyncPoll } = require('async-poll');

/** Fetch news from a mock URL */
const fn = async () => fetch('https://example.com/api/news').then(r => r.json());
/** Keep polling until the more than 100 `news` are received or `status` returns `complete` */
const conditionFn = d => d.data.news.length > 100 || d.data.status === 'complete';
/** Poll every 2 seconds */
const interval = 2e3;
/** Timeout after 30 seconds and returns end result */
const timeout = 30e3;

asyncPoll(fn, conditionFn, { interval, timeout })
  .then(console.log)
  .catch(console.error);

Browser

ES Modules

<script type="module">
  import { asyncPoll } from 'https://unpkg.com/async-poll@latest/dist/async-poll.js';

  /** Fetch news from a mock URL */
  const fn = async () => fetch('https://example.com/api/news').then(r => r.json());
  /** Keep polling until the more than 100 `news` are received or `status` returns `complete` */
  const conditionFn = d => d.data.news.length > 100 || d.data.status === 'complete';
  /** Poll every 2 seconds */
  const interval = 2e3;
  /** Timeout after 30 seconds and returns end result */
  const timeout = 30e3;

  asyncPoll(fn, conditionFn, { interval, timeout })
    .then(console.log)
    .catch(console.error);
</script>

IIFE

<script src="https://unpkg.com/async-poll@latest/dist/async-poll.iife.js"></script>
<script>
  const { asyncPoll } = window.AsyncPoll;

  /** Fetch news from a mock URL */
  const fn = async () => fetch('https://example.com/api/news').then(r => r.json());
  /** Keep polling until the more than 100 `news` are received or `status` returns `complete` */
  const conditionFn = d => d.data.news.length > 100 || d.data.status === 'complete';
  /** Poll every 2 seconds */
  const interval = 2e3;
  /** Timeout after 30 seconds and returns end result */
  const timeout = 30e3;

  asyncPoll(fn, conditionFn, { interval, timeout })
    .then(console.log)
    .catch(console.error);
</script>

Performance Timing/ Timeline API via PerformanceObserver

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. */
import { PerformanceObserver } from 'perf_hooks';

async function main() {
  let measurements: Record<string, unknown> = {};
  const perfObs = new PerformanceObserver((list) => {
    for (const n of list.getEntries()) {
      measurements[n.name] = n.duration;
    }
  });
  perfObs.observe({ entryTypes: ['measure'] });
  const d = await asyncPoll(fn, conditionFn, { interval, timeout });
  perObs.disconnect();

  return {
    data: d,
    measurements,
  };
}

API Reference

AsyncPollOptions

interface AsyncPollOptions {
  interval: number;
  timeout: number;
}

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. If true, the polling stops and returns with a value in the type of T.
  • options <AsyncPollOptions> Polling options.
    • interval <number> Polling interval.
    • timeout <number> Timeout.
  • returns: <Promise<T>> Promise which resolves with a value in the type of T.

License

MIT License © Rong Sen Ng (motss)

FAQs

Package last updated on 04 May 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts