tcf4gg
Last Updated: February 25, 2016
·
1.478K
· camachgk

Multi-Try $.promise

This method wraps a provided callback that returns a jQuery promise (or jqXHR object) and allows that asynchronous functionality to fail and be retried without rejecting the returned promise.

multiTryPromise = (callback, numberOfTries, evaluate, options) ->
  deferred = $.Deferred()

  retry = =>
    if deferred.state() is 'pending' and 
      numberOfTries and 
      (not evaluate? or evaluate arguments)

      numberOfTries--
      callback(options).then deferred.resolve, retry
    else
      deferred.rejectWith @, arguments

  numberOfTries--
  callback(options).then deferred.resolve, retry

  deferred.promise()