在回调中进行回调
问题描述:
我有一个异步操作的问题。我需要知道我的表何时生成。但是该表是从通过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();
}
答
试试这个
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){' –
答
你可以连续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>
的$就调用返回一个承诺,所以你可以链这一承诺与您要执行的下一个动作/功能的分辨率。
您是否必须使用回调?你能够使用[Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)或[异步函数](https://developer.mozilla.org/EN-US /文档/网络/的JavaScript /参考/语句/ async_function)? – wing
这就是为什么我们发明了Promises。将第二个回调函数添加到第一个函数ajax调用中:'success:function(response){callback(response,otherCallback);}'和'getRepairBook(function(response),otherCallback)'您可以尽可能深的嵌套,最终与毁灭之谜。 ;) – Shilly