Created
November 20, 2015 22:53
-
-
Save daviddulak/f51b05b1d7721a2ea775 to your computer and use it in GitHub Desktop.
Static utility for forcing a minimum return time for 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 forcing a minimum return time for a promise | |
* @class MinimumDelayedPromise | |
*/ | |
/** | |
* 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} minimumDelay The minimum number of milliseconds | |
* | |
* @return {Promise} A new jQuery Deffered promise that resolves just as the original would have | |
*/ | |
return function MinimumDelayedPromise(context, func, args, minimumDelay) { | |
var promise = $.Deferred(); | |
var hasReachedMinimumDelay = false; | |
var hasResolved = false; | |
var resolvedArguments = []; | |
var hasRejected = false; | |
var rejectedArguments = []; | |
setTimeout(function() { | |
hasReachedMinimumDelay = true; | |
if (hasResolved) { | |
promise.resolve.apply(context, resolvedArguments); | |
} | |
if (hasRejected) { | |
promise.reject.apply(context, rejectedArguments); | |
} | |
}.bind(this), minimumDelay); | |
func.apply(context, args).then( | |
function success() { | |
hasResolved = true; | |
resolvedArguments = arguments; | |
if (hasReachedMinimumDelay) { | |
promise.resolve.apply(context, arguments); | |
} | |
}.bind(this), | |
function error() { | |
hasRejected = true; | |
rejectedArguments = arguments; | |
if (hasReachedMinimumDelay) { | |
promise.reject.apply(context, arguments); | |
} | |
}.bind(this)); | |
return promise; | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment