Skip to content

Instantly share code, notes, and snippets.

@marshall007
Created July 28, 2014 20:15
Show Gist options
  • Select an option

  • Save marshall007/325a805983414f2c8e72 to your computer and use it in GitHub Desktop.

Select an option

Save marshall007/325a805983414f2c8e72 to your computer and use it in GitHub Desktop.
Retries with exponential backoff using Bluebird
_ = require 'lodash'
Promise = require 'bluebird'
Promise.retry = (action, options = {}) ->
_.merge
max: 5
backoff: 500
, options
d = Promise.defer()
do_action = (attempt, err) ->
if attempt > options.max
return d.reject err
Promise.delay options.backoff * attempt
.then action
.then (data) ->
return d.resolve data
, (err) ->
return do_action attempt++, err
process.nextTick ->
do_action 0
return d.promise
# Example Usage
Request = Promise.promisifyAll (require 'request')
retry_options =
max: 3
backoff: 1000
Promise.retry ->
Request.getAsync 'http://example.com'
, retry_options
.spread (res, data) ->
# carry on
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment