user2734550 user2734550 - 3 months ago 12
Ajax Question

Why jquery then callback is running before deferred is resolved?

I am trying to implement a load more ajax function. However, whenever the button is clicked, it runs the function inside then() before deferred object is resolved. I had to use setTimeout in then to make it work. I don't think this is a correct way since it makes then() completely meaningless ? Can anyone take a look what's going on please? Thanks.

$(document).on('click', '.c-button--lg', function() {

var appendHTML = function () {
var $dfd = $.Deferred();
$.get(nextLink, function(html) {
$pillarContainer.append(html);
console.log(0);
$dfd.resolve();
});
return $dfd.promise();
};

appendHTML().then(function(){
console.log(1); //This is running before console.log(0);
});
});

Answer

Because you define appendHTML, but call appendData() in your code example, it is not clear what appendData() in your code actually does.

If you meant for appendHTML and appendData to be the same function name in your question, then you can vastly simplify what you have like this and also avoid the promise anti-pattern of wrapping an existing promise in another unnecessary promise/deferred (and also avoid the bugs you introduced by doing that because you don't have proper error handling). And, it should not have the problem you report either.

This code just returns the promise that $.get() already returns and it uses that promise to process the result so you're consistently using promises (not mixing promises with custom jQuery callbacks):

   $(document).on('click', '.c-button--lg', function () {

       // define $pillarContainer somewhere in here

       function appendData() {
           return $.get(nextLink).then(function(html) {
               $pillarContainer.append(html);
               console.log(0);
               return html;
           });
       };

       appendData().then(function () {
           console.log(1); //This is running before console.log(0);
       });
   });
Comments