Search code examples
jquerypromisedeferred

Understanding Problem - Jquery Deferred chaining


function ajax_call() {

    var ajaxCallMock = $.Deferred().resolve('A');

    return ajaxCallMock.done(function(response) {

            return 'B';

    });
}



ajax_call().done(function(response) {
    console.log(response);
});

I would expect the console output to be 'B', but I get 'A'. Why?


Solution

  • Use then() instead of done() as done doesn't return a new promise.

    function ajax_call() {
    
      var ajaxCallMock = $.Deferred().resolve('A');
    
      return ajaxCallMock.then(function(response) {
        return 'B';
      });
    }
    
    
    
    ajax_call().then(function(response) {
      console.log(response);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>