@srsl/tools
Version:
JavaScript tools for common interfaces
28 lines (26 loc) • 663 B
JavaScript
const sleep = require('./sleep')
module.exports = async ({
attempts,
interval,
connect,
onError,
}) => {
if (attempts === undefined) attempts = Infinity
if (interval === undefined) interval = 3000 /* ms */
if (connect === undefined) connect = () => {}
if (onError === undefined) {
onError = (error) => {
console.error('Connection error.', error)
throw new Error('Failed to connect')
}
}
if (attempts === 0) return onError()
try {
return connect()
} catch (e) {
console.log('onError: ', attempts)
onError(e, attempts)
await sleep(interval)
return run(connectionString, attempts - 1, interval)
}
}