1

I have a function that expects a promise which should resolve with 3 arguments.

The problem is that the function that returns the promise must wait for another deferred

function load(){
  var d = $.Deferred();

  this.getData().then(function(){
    ....
    d.resolve(1, 2, 3);
  });

  return d.promise();
}


load().then(function(a, b, c){
  ....
});

Is there any way I can use the promise that is already returned by getData() and avoid creating another deferred object? The problem is that the promise returned by getData is resolved before then() is called and I don't know how to resolve it again with new arguments

xpedobearx
  • 707
  • 3
  • 8
  • 13
  • If the promise that is already returned by `getData` does not fulfill with `(1, 2, 3)`, then you cannot use it - a promise must only be resolved once. There's nothing wrong with creating a new deferred for this, however it should look [like this](http://stackoverflow.com/a/21113451/1048572) instead of using the [deferred antipattern](http://stackoverflow.com/q/23803743/1048572). – Bergi Nov 23 '15 at 02:14

1 Answers1

3

You don't need the extra deferred you are creating. Just return the promise you already have from your outer function and then return a value from within the .then() handler. The value you return from within the .then() handler becomes the newly resolved value of the returned promise. This is promise chaining and you can implement it like this:

function load(){
  return this.getData().then(function(){
    ....
    return [1, 2, 3];
  });
}


load().then(function(array){
    console.log(array);    // [1,2,3]
});

FYI, note that I changed the return value to an array of values since you can only return a single value/object from a function. That means that the value that comes through in load().then(...) will be that array.

jfriend00
  • 683,504
  • 96
  • 985
  • 979