2017-06-29 84 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

相关问题