0

我有一个这样的循环,如果 ajax 请求成功,它应该返回并退出循环,它也应该只重试 10 次,但它只是迭代循环 10 次,然后在请求成功时停止。

retryCount = 0

while (retryCount < 10)
  $.ajax
    type: "GET"
    url: "http://" + proxyURL + "?"
    dataType: "jsonp"
    data:
      url:
        url + "?" + method + "&" + $.param
          parameters: JSON.stringify parameters
    success: (response) ->
      data = response

      console.log "----------"
      console.log "METHOD: " + method
      console.log parameters
      console.log data
      console.log "----------"

      if data.contents.fault
        if data.contents.fault.code is 256
          console.log "fetching new token (" + retryCount + ")"
          fetchNewToken ->
            return callback(data.contents.result)
        else
          console.log "ERROR: " + $.trim(data.contents.fault.message)

      if data.contents.result
        if data.contents.result instanceof Array
          if data.contents.result.length > 0
            return callback(data.contents.result)
        else
          return callback(data.contents.result)
      else
        console.log "retrying " + method + " (" + retryCount + ")"

    retryCount++
4

2 回答 2

1

我看起来你没有异步编程的概念。

这就是发生的事情:

retryCount = 0
# TIMESTAMP 0
while (retryCount < 10)
  # TIMESTAMP 1, 3, 5, ...
  $.ajax
    url: "http://" + proxyURL + "?"
    dataType: "jsonp"
    success: (response) ->
      #TIMESTAMP very later, long after your loop is through

  # TIMESTAMP 2, 4, 6, ...
  retryCount++

它应该以某种方式相关看起来像这样(只是一个例子,一种伪代码):

retryCount = 0
loadData = (retryCount, callBack, errorCallBack) ->
  $.ajax
    url: "asdasdasd"
    success: () ->
      callBack someDataYouRecieved
    error: () ->
      retryCount++
      if retryCount is 10
        errorCallBack "got 10 errors"
      else
        loadData retryCount, callBack


loadData retryCount, successHandler, errorHandler
于 2013-05-17T14:06:10.023 回答
0

如果我理解正确,这样的构造应该可以解决问题(省略特定于域的部分):

MAX_RETRIES = 10

issueRequestWithRetries = (request, retries=0) ->
  request.success = (response) ->
    # do something, then find out that you need to retry
    if retries < MAX_RETRIES
      issueRequestWithRetries(request, retries+1)
    else
      # handle the error
  $.ajax request

# sample usage
issueRequestWithRetries
  type: "GET"
  url: "http://" + proxyURL + "?"
  dataType: "jsonp"
  data: {} # real data
于 2013-05-17T14:08:52.397 回答