项目作者: motss

项目描述 :
Async polling with condition and timeout
高级语言: TypeScript
项目地址: git://github.com/motss/async-poll.git
创建时间: 2018-09-29T07:35:19Z
项目社区:https://github.com/motss/async-poll

开源协议:MIT License

下载


🚨 No longer maintained. Moved to @reallyland/node_mod. 🚨


async-poll



Advanced polling module with timeout and metrics collection



Buy Me A Coffee
@igarshmyb"">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

  1. # Install via NPM
  2. $ npm install --save async-poll

Usage

TypeScript or native ES modules

  1. interface NewsData {
  2. data: {
  3. news: object[];
  4. status: number;
  5. };
  6. }
  7. import asyncPoll from 'async-poll';
  8. /** Fetch news from a mock URL */
  9. const fn = async () => fetch('https://example.com/api/news').then(r => r.json());
  10. /** Keep polling until the more than 100 `news` are received or `status` returns `complete` */
  11. const conditionFn = (d: NewsData) => d.data.news.length > 100 || d.data.status === 'complete';
  12. /** Poll every 2 seconds */
  13. const interval = 2e3;
  14. /** Timeout after 30 seconds and returns end result */
  15. const timeout = 30e3;
  16. asyncPoll<NewsData>(fn, conditionFn, { interval, timeout })
  17. .then(console.log)
  18. .catch(console.error);

Node.js

  1. const { asyncPoll } = require('async-poll');
  2. /** Fetch news from a mock URL */
  3. const fn = async () => fetch('https://example.com/api/news').then(r => r.json());
  4. /** Keep polling until the more than 100 `news` are received or `status` returns `complete` */
  5. const conditionFn = d => d.data.news.length > 100 || d.data.status === 'complete';
  6. /** Poll every 2 seconds */
  7. const interval = 2e3;
  8. /** Timeout after 30 seconds and returns end result */
  9. const timeout = 30e3;
  10. asyncPoll(fn, conditionFn, { interval, timeout })
  11. .then(console.log)
  12. .catch(console.error);

Browser

ES Modules

  1. <script type="module">
  2. import { asyncPoll } from 'https://unpkg.com/async-poll@latest/dist/async-poll.js';
  3. /** Fetch news from a mock URL */
  4. const fn = async () => fetch('https://example.com/api/news').then(r => r.json());
  5. /** Keep polling until the more than 100 `news` are received or `status` returns `complete` */
  6. const conditionFn = d => d.data.news.length > 100 || d.data.status === 'complete';
  7. /** Poll every 2 seconds */
  8. const interval = 2e3;
  9. /** Timeout after 30 seconds and returns end result */
  10. const timeout = 30e3;
  11. asyncPoll(fn, conditionFn, { interval, timeout })
  12. .then(console.log)
  13. .catch(console.error);
  14. </script>

IIFE

  1. <script src="https://unpkg.com/async-poll@latest/dist/async-poll.iife.js"></script>
  2. <script>
  3. const { asyncPoll } = window.AsyncPoll;
  4. /** Fetch news from a mock URL */
  5. const fn = async () => fetch('https://example.com/api/news').then(r => r.json());
  6. /** Keep polling until the more than 100 `news` are received or `status` returns `complete` */
  7. const conditionFn = d => d.data.news.length > 100 || d.data.status === 'complete';
  8. /** Poll every 2 seconds */
  9. const interval = 2e3;
  10. /** Timeout after 30 seconds and returns end result */
  11. const timeout = 30e3;
  12. asyncPoll(fn, conditionFn, { interval, timeout })
  13. .then(console.log)
  14. .catch(console.error);
  15. </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.

  1. /** For Node.js **only**, no import is required on browser. */
  2. import { PerformanceObserver } from 'perf_hooks';
  3. async function main() {
  4. let measurements: Record<string, unknown> = {};
  5. const perfObs = new PerformanceObserver((list) => {
  6. for (const n of list.getEntries()) {
  7. measurements[n.name] = n.duration;
  8. }
  9. });
  10. perfObs.observe({ entryTypes: ['measure'] });
  11. const d = await asyncPoll(fn, conditionFn, { interval, timeout });
  12. perObs.disconnect();
  13. return {
  14. data: d,
  15. measurements,
  16. };
  17. }

API Reference

AsyncPollOptions

  1. interface AsyncPollOptions {
  2. interval: number;
  3. timeout: number;
  4. }

asyncPoll\(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 in milliseconds. When timeout is less than 1, this indicates a infinite polling.
  • returns: <Promise<T>> Promise which resolves with a value in the type of T.

License

MIT License © Rong Sen Ng (motss)