2017-06-29 140 views
0

我有一個Ajax調用,我想多次運行,直到它滿足特定的條件。 AJAX調用爲您提供作業狀態 - 運行,排隊和完成。 我無法獲得工作狀態 - 完成。獲得運行狀態後,需要幾分鐘才能獲得狀態「完成」。到目前爲止,我已經嘗試了以下JS。我也想在if條件滿足後打破循環。我也不確定我是否應該接聽100次電話,因爲這可能需要更多的時間。感謝您的幫助。如何多次運行javascript函數,直到滿足if條件

我的JS:

var pollForJob= gallery.getJob(jobId, function(job){ 
    var jobStat=job.status; 
    console.log(jobStat); 
    if(jobStat=="Complete"){ 
     alert("Complete"); 
    } else { 
    // Attempt it again in one second 
     setTimeout(pollForJob, 1000); 
     console.log("still working"); 
     console.log(jobStat); 
    } 
}, function(response){ 
    var error = response.responseJSON && response.responseJSON.message || 
       response.statusText; 
    alert(error); 
    // Attempt it again in one second 
    setTimeout(pollForJob, 1000); 
}); 
+0

看'承諾'。如果沒有使用'setInterval'來檢查條件。 –

+1

這叫做長輪詢,基本上就是錘擊服務器,直到它給你你正在等待的價值。更聰明的方法是使用websocket,這將允許服務器在完成時通知客戶端。 –

+0

調用它100次似乎是一個壞主意...... – epascarello

回答

1

就像傑里米Thille說,這就是所謂的長輪詢。這樣做的一個簡單方法是創建一個將呼叫發送到服務器的功能。然後,如果失敗,請使用setTimeout稍後再排隊另一個請求。

function pollForJob() { 
    gallery.getJob(jobId, function(job) { 
     var jobStat = job.status; 
     if (jobStat == "Complete") { 
      alert("Complete"); 
     } else { 
      // Attempt it again in one second 
      setTimeout(pollForJob, 1000); 
     } 
    }, function(response) { 
     var error = response.responseJSON && response.responseJSON.message || response.statusText; 
     console.error(error); 
     // Attempt it again in one second 
     setTimeout(pollForJob, 1000); 
    }); 
} 
pollForJob(); 
+0

爲什麼浪費1秒? – Priya

+1

@Priya它不必那麼長。如果你認爲在此之前你會得到迴應,那就去做吧。但是,如果您不希望在200毫秒內得到有效的響應,則每隔50毫秒打一次服務器都沒有意義。 –

+0

您好邁克,感謝您的答案,由於某種原因,此解決方案無法正常工作。我也試過setInterval。它只是沒有檢測到如果條件 – dpr

相關問題