Created
November 20, 2015 21:53
-
-
Save daviddulak/adcc9b33904798406e8e to your computer and use it in GitHub Desktop.
Static utility for retrying a jQuery Deferred promise
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
define(function(require) { | |
var $ = require('$'); | |
/** | |
* Static utility for retrying a promise | |
* @class PromiseToRetry | |
*/ | |
/** | |
* A promise based helper function | |
* @method PromiseToRetry | |
* @param {Context} context The context to be bound | |
* @param {function} func The function to be retried | |
* @param {Array} args The array of arguments that would have been sent to the function | |
* @param {Number} maxRetries The number of times to retry | |
* | |
* @return {Promise} A new jQuery Deffered promise that resolves just as the original would have | |
*/ | |
return function PromiseToRetry(context, func, args, maxRetries) { | |
var promise = $.Deferred(); | |
var retryCount = 0; | |
var _attempt = function() { | |
func.apply(context, arguments).then( | |
function success() { | |
//console.log('immediate success'); | |
promise.resolve.apply(this, arguments); | |
}.bind(this), | |
function error() { | |
//console.log('failed '+retryCount+' out of '+ maxRetries +' times'); | |
if (retryCount >= maxRetries) { | |
//console.log('failed '+retryCount+' times'); | |
promise.reject.apply(this, arguments); | |
} else { | |
retryCount++; | |
_attempt.apply(this, args); | |
} | |
}.bind(this) | |
).progress( | |
function progress() { | |
promise.notify.apply(this, arguments); | |
}); | |
}; | |
_attempt.apply(this, args); | |
return promise; | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment