Created
July 24, 2015 10:24
-
-
Save gigablah/e8d703a7ffa5b043c231 to your computer and use it in GitHub Desktop.
Bluebird async test
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
global.P = require 'bluebird' | |
backoff = 100 | |
max_attempts = 10 | |
_random_time = -> Math.random() * 3000 + 1000; | |
_backoff = (attempt) -> if attempt > 0 then backoff * Math.pow(2, attempt-1) else 0 | |
_with_retry = (err, attempt, res, rej, callback) -> | |
return rej(err) if attempt >= max_attempts | |
P.try -> | |
return unless err? | |
console.info err | |
grants = [do_stuff('grant1', 1), do_stuff('grant2', 1)] | |
P.settle(grants) | |
.delay _backoff(attempt) | |
.then -> | |
callback res, (err) -> | |
console.info "Retry attempt: #{attempt + 1}" | |
_with_retry err, ++attempt, res, rej, callback | |
do_stuff = (name, chance) -> | |
new P (res, rej) -> | |
_with_retry null, 0, res, rej, (resolve, reject) -> | |
get_result = -> | |
roll = Math.random() | |
if roll < chance | |
resolve task: name, status: 'ok', roll: roll | |
else | |
reject task: name, status: 'error', roll: roll | |
delay = _random_time() | |
console.info "Trying: #{name}... [#{delay}]" | |
timer = setTimeout get_result, delay | |
#timer.unref() | |
P.try -> | |
do_stuff('task1', 0.2) | |
.then (res) -> console.info res | |
return 'hello' | |
.then (res) -> | |
console.info res | |
do_stuff('other_task', 1) | |
.then (res) -> | |
console.info res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment