2013-05-17 36 views
0

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

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

它是**异步**,所以你不能使用while循环。注意'success'是一个回调*函数* - 容易在coffescript中丢失 – Bergi

+0

在ajax请求中设置'async:false'时,我也会发生同样的情况。什么是替代方法,解决它? – Marius

回答

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 
+0

谢谢,作品! – Marius

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