Last active
January 12, 2016 04:25
-
-
Save lsongdev/6e3e1ec0380956006cd1 to your computer and use it in GitHub Desktop.
catch promise error and retry .
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
const debug = require('debug')('promise-retry'); | |
/** | |
* [promise-retry: catch promise error and retry] | |
* @param {[type]} task [description] | |
* @param {[type]} n [description] | |
* @param {[type]} timeout [description] | |
* @return {[type]} [description] | |
* @source https://gist.github.com/song940/6e3e1ec0380956006cd1 | |
*/ | |
module.exports = function retry(task, n, timeout){ | |
var timeouts = []; | |
if(/array/i.test(({}).toString.call(n))){ | |
timeouts = n; | |
}else{ | |
while(n--) timeouts.push(timeout || 1000); | |
} | |
return new Promise(function(accept, reject){ | |
(function fn(){ | |
task(this).then(accept, function(err){ | |
if(timeouts.length){ | |
timeout = timeouts.shift(); | |
debug('%ss after retry', timeout / 1000); | |
setTimeout(fn, timeout); | |
} else reject(err); | |
}); | |
})(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment