Last Updated: July 16, 2021
·
1.627K
· 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()