problem:
plz help me out :) thanks. i tried several-codes and learn (deferred obj, queue, pipe, when, then, done) but it seems im missing something.
$('#button').click(function() {
$.when(
//(fx-1)getDB-Records()
$.ajax({
url: '/echo/html/',
success: function(data) {
//call (fx-2) just populate table without formating
populateTable(data);
}
})
).then( function(){
//(fx-3) formatTable()
console.log('Problem: Format table starts before population of Table');
});
});
function populateTable(data){
//(fx-2) just populate table without formating
//takes a little time
setTimeout(function (){console.log('populate Table'); }, 1);
}
Several points :
$.ajax()
in $.when()
. $.ajax()
returns an inherently promise-compatible object with chainable .done()
, .fail()
, .always()
and .then()
methods. $.ajax()
became promise-compatible, use of the success:
callback (in the options map) became unnecessary. It remains only for backward compatibility and may one day be removed. Mixing the old approach with the new is not recommended. populateTable()
call is not necessary. You can specify populateTable
by name. populateTable()
must return a Promise (to a chained .then()
) in order for something to happen after its asynchronous activity has completed. You probably want something like this :
$('#button').click(function() {
//(fn-1)getDB-Records()
$.ajax({
url: '/echo/html/'
}).then(populateTable).done(function(txt) {
//(fn-3) formatTable()
console.log('populateTable reports: ' + txt);
});
});
function populateTable(data) {
//(fn-2) just populate table without formatting
var dfrd = $.Deferred();
setTimeout(function () {
var message = 'Table populated';
console.log('populateTable says: ' + message);
dfrd.resolve(message);
}, 1);
return dfrd.promise();
}
I resolve my query but still open for any good solution/suggestion :)
//Entry point
populate($("#mytable"), fmtTblFilter);
--- or ---
populate($("mySelectBox"), $.noop());
function getdB(elem){
return $.ajax({
type: "POST",
url: url,
dataType: "json",
});
}
function populate(elem, callback){
var dBRet;
dBRet = getdB(elem);
dBRet.success(function(data) {
switch (elem.get(0).tagName) {
case 'SELECT':
populateSelect(elem, data);
break;
case 'TABLE':
populateTable(elem, data).pipe(callback);
break;
default:
break;
}
});
}
function populateTable(elem, data){
var d = $.Deferred();
//code here
d.resolve();
return d.promise();
}
function fmtTblFilter(){
var d = $.Deferred();
//code here
d.resolve();
return d.promise();
}
function populateSelect(elem, data){
//code here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.