在下面的代碼的API execute_wc
叫,接着調用遞歸函數poll_results
和返回時,纔會有一個狀態!= 1。現在,當功能poll_results
被稱爲是異步的,因此if else
條件submit_stat
不executed.how來處理這種情況的jQuery做同步調用和執行
function submit_stat(){
var poll_status = '';
$.post("/reports/execute_wc/", snddata,
function callbackHandler(data, textstatus)
{
console.log('got response');
if (data.status == 0)
{
poll_status = poll_results();
if (poll_status == 1){
}
else if(poll_status == 0)
{
alert('Error while processing data.Please check input files');
}
}
else if (data.status == 1)
{
alert('Error while processing data');
}
},
"json"
);
}
function poll_results(){
$.post('/reports/poll_wcstatus/', function(data) {
if(data.wce_status == 1){
return setTimeout(poll_results,5000);
}
else if (data.wce_status != 1 || data.wce_status != 3)
{
alert('return 1');
return 1;
}
else
{
alert('return 0');
return 0;
}
});
}
編輯1:
function poll_results(callback){
var callback='';
$.post('/reports/poll_wcstatus/', function(data) {
//alert(data); // process results here
console.log(data);
console.log(data.wce_status);
if(data.wce_status == 1){
return setTimeout(poll_results,5000);
}
else if (data.wce_status != 1 || data.wce_status != 3){
alert('return 1');
//return 1;
callback(1);
}
else //3 is fatal error shoul
{
alert('return 0');
callback(0);
//return 0;
}
});
}
$.post("/reports/execute_wc/", snddata,
function callbackHandler(data, textstatus)
{
console.log('got response');
if (data.status == 0)
{
alert('starting script');
//poll_status = poll_results();
poll_results(function(poll_status){
if (poll_status == 1){
alert('Content extratcted.Please download the results file');
$('#loading').hide();
$('#downloadfile').show();
$('#downloadfile').html('').append('<a href="'+ data.url +'">Download output</a>');
}
else if(poll_status == 0)
{
$('#loading').hide();
alert('Error while processing data.Please check input files');
}
});
}
else if (data.status == 1)
{
$('#loading').hide();
alert('Error while processing data');
}
},
"json"
);
您可以在調用poll_results時使用回調函數。 – MacMac
可以舉一個例子 – Rajeev