2017-02-20 65 views
0

我有一個異步操作的問題。我需要知道我的表何時生成。但是該表是從通過ajax獲取的數據庫信息生成的。在回調中進行回調

這將是我的起點,在那裏我需要知道數據被取出並生成表:

generateTable(function(r){ 

}); 

在這裏我從數據庫獲取信息,並將其發送給回調函數

function getRepairBook(callback) { 
      $.ajax({ 
       method: "GET", 
       dataType: "json", 
       contentType: "application/json", 
       url: "x", 
       success: function(response){ 
        callback(response); 
       }, 
       error: function(response){ 

       } 
      }); 
     } 

這裏我需要一個回調函數。但我不知道該怎麼做:

function generateTable(callback) { 

//callback of AJAX 
    getRepairBook(function (response) { //, callback 

    console.log(response); 
    $('#repTable >tbody').html(""); 

    var trHTML = ''; 
    $.each(response, function (i, item) { 

     //... 
     //build table 
    }); 
    $('#repTable >tbody').append(trHTML); 
    //need a callback of this callback function 
    //callback(); 
    }); 

    callback(); 
} 
+0

您是否必須使用回調?你能夠使用[Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)或[異步函數](https://developer.mozilla.org/EN-US /文檔/網絡/的JavaScript /參考/語句/ async_function)? – wing

+1

這就是爲什麼我們發明了Promises。將第二個回調函數添加到第一個函數ajax調用中:'success:function(response){callback(response,otherCallback);}'和'getRepairBook(function(response),otherCallback)'您可以儘可能深的嵌套,最終與毀滅之謎。 ;) – Shilly

回答

0

試試這個

function getRepairBook(callback) { 
      $.ajax({ 
       method: "GET", 
       dataType: "json", 
       contentType: "application/json", 
       url: "x", 
       success: function(response){ 
        callback(response); 
        generateTable(response);//calling this on success of ajax call 
       }, 
       error: function(response){ 

       } 
      }); 
     } 
+0

我也想過這個,但我需要它作爲變量,如上所示。在生成表後,我需要執行不同的操作 – BayLife

+0

然後將'getRepairBook(function(response){'''getRepairBook(function(callback){' –

0

你可以連續JQuery deferred對象。 他們的工作是這樣的:

function foo() { 
 
    // initialize the deferred 
 
    var dfd = $.Deferred(); 
 
    
 
    // resolve the deferred after 2 sec 
 
    setTimeout(function() { 
 
    dfd.resolve(); 
 
    }, 2000); 
 
    
 
    // return the promise 
 
    return dfd.promise(); 
 
} 
 

 
function bar() { 
 
    var dfd = $.Deferred(); 
 
    // resolve the deferred after 1 sec 
 
    setTimeout(function() { 
 
    dfd.resolve(); 
 
    }, 1000); 
 
    return dfd.promise(); 
 
} 
 

 
$(function() {  
 
    var dfd = foo(); 
 
    // when foo has been resolved 
 
    dfd.then(function() { 
 
    alert('foo has been resolved'); 
 
    var dfd2 = bar(); 
 
    // when bar has been resolved 
 
    dfd2.then(function() { 
 
     alert('bar has been resolved'); 
 
    }); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

的$就調用返回一個承諾,所以你可以鏈這一承諾與您要執行的下一個動作/功能的分辨率。