Skip to content

Instantly share code, notes, and snippets.

@onnorh
Forked from ivan-marquez/polling.js
Last active January 4, 2024 19:43

Revisions

  1. @ivan-marquez ivan-marquez revised this gist Jul 24, 2019. No changes.
  2. @ivan-marquez ivan-marquez created this gist Jul 18, 2019.
    65 changes: 65 additions & 0 deletions polling.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@
    const axios = require('axios').default;

    function getAPIClient() {
    const axiosConfig = {
    baseURL: 'https://csrng.net/csrng/csrng.php',
    timeout: 5000,
    };

    return axios.create(axiosConfig);
    }

    function getData() {
    const client = getAPIClient();
    return client.get('/?min=0&max=100');
    }

    // create a promise that resolves after a short delay
    function delayPromise(ms) {
    return new Promise(function(resolve) {
    setTimeout(resolve, ms);
    });
    }

    // cb is the callback function
    // interval is how often to poll
    // timeout is how long to poll waiting for a result (0 means try forever)
    function poll(cb, predicate, errorHandler, interval, timeout) {
    let start = Date.now();

    function run() {
    return cb().then(function({ data }) {
    console.log('data:', data);
    if (predicate(data)) {
    // we know we're done here, return from here whatever you
    // want the final resolved value of the promise to be
    return data;
    } else {
    if (timeout !== 0 && Date.now() - start > timeout) {
    errorHandler();
    } else {
    // run again with a short delay
    return delayPromise(interval).then(run);
    }
    }
    });
    }
    return run();
    }

    function isGreaterThan90([number]) {
    return number.random > 90;
    }

    function errorHandler() {
    throw new Error('timeout error on poll');
    }

    function logResult(data) {
    data = JSON.stringify(data, null, 2);
    console.log(`result: ${data}`);
    }

    poll(getData, isGreaterThan90, errorHandler, 1000, 30 * 1000)
    .then(logResult)
    .catch(console.error);