Search code examples
jquerydeferred

How do I return a value from a jQuery deferred chain?


Given this example, I was hoping that hello world would be bubbled up the chain. Certain Deferred/Promise frameworks can though, but it seems like jQuery can't do this.

function function1() {
  return function2().done(function(pelle) {
    return "hello world";
  });
}

function function2() {
  return $.Deferred().resolve("function2");
}

function1().done(function(response) {
  console.log("response", response);
});

https://jsfiddle.net/ysbjr1nm/

How can I refactor this code to achieve this?


Solution

  • Using wrong callback method in function1. You want then not done

    Promise chains work by return in then returning to next then in the chain

    function function1() {
      return function2().then(function(pelle) {
        return "hello world";
      });
    }
    

    DEMO