1
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?

4
  • Because you can only resolve a promise once AFAIK Commented Apr 9, 2019 at 12:51
  • 1
    I think a resolved promise always returns another solved promise, is that wrong? Commented Apr 9, 2019 at 12:53
  • Oh, I missed the done part, sorry Commented Apr 9, 2019 at 12:54
  • jQuery's .done() is not a synonym for .then(). There are few if any cases where you would use .done(). Commented Apr 9, 2019 at 18:02

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Can I simply replace the var ajaxCallMock = $.Deferred().resolve('A'); with a $.get() Ajax Call? and still use then?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.