Why jquery then callback is running before deferred is resolved?

时间:2016-08-31 17:31:15

标签: jquery ajax

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);
            });
        });

1 个答案:

答案 0 :(得分:1)

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);
       });
   });