Last active
February 3, 2024 00:13
-
-
Save ivan-marquez/e141b863bc77c1e6e9a4f0c30d72ee0a to your computer and use it in GitHub Desktop.
Long polling implementation in Js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment