Created
July 28, 2014 20:15
-
-
Save marshall007/325a805983414f2c8e72 to your computer and use it in GitHub Desktop.
Retries with exponential backoff using Bluebird
This file contains hidden or 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
| _ = 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