我有一个像这样的循环,如果ajax请求成功,它应该返回并退出循环,它也应该只重试10次,但它只是迭代循环10次,然后在请求成功时停止。 / p>
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++
答案 0 :(得分: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
答案 1 :(得分: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