Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import async from 'async'
export default class RetryQueue {
constructor (strategy, opts = {}) {
const options = Object.assign({
times: 14,
interval (retryCount) {
return 1000 * Math.pow(2, retryCount)
}
}, opts)
const retryableStrategy = async.retryable(options, strategy)
this.queue = async.queue(retryableStrategy, 1)
}
push (task) {
return new Promise((resolve, reject) => {
return this.queue.push(task, (err, result) => {
if (err) return reject(err)
return resolve(result)
})
})
}
}
import test from 'ava'
import RetryQueue from '../retry-queue.js'
test('RetryQueue handles items', async t => {
const strategy = async function (str) {
return str.toUpperCase()
}
const queue = new RetryQueue(strategy)
const result = await queue.push('my task')
t.is(result, 'MY TASK')
})
test('RetryQueue retries failed items', async t => {
let tryCount = 0
const strategy = async function (str) {
if (tryCount < 5) {
tryCount += 1
throw new Error('Too few fails')
}
return str.toUpperCase()
}
const queue = new RetryQueue(strategy, { interval: 50 })
const result1 = await queue.push('one')
const result2 = await queue.push('two')
t.is(result1, 'ONE')
t.is(result2, 'TWO')
t.is(tryCount, 5)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.