0

我有一个 Ajax 调用,我想多次运行它,直到它满足特定的 if 条件。AJAX 调用为您提供作业状态 - 正在运行、已排队和已完成。我无法获得作业状态 - 完成。获得运行状态后,需要几分钟才能获得状态完成。到目前为止,我已经尝试了以下 JS。我还想在满足 if 条件后打破循环。我也不确定我是否应该运行 100 次电话,因为它可能需要更多时间。谢谢您的帮助。

我的 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);
});
4

1 回答 1

1

就像 Jeremy Tille 说的,这叫做长轮询。一种简单的方法是创建一个调用服务器的函数。然后,如果它失败了,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();
于 2017-06-29T19:32:50.467 回答