1

How to resolve one Deffered object with resolve state of another. Simple example and simple explanation please (saw a lot of difficult ones).

How I can resolve result promise with a foo(), without .done(..) and .fail(..)?

var result = $.Deferred();

/**
 * @returns {Deferred}
 */
var foo = function() {
  // ... something that returns deferred object at random moment of time
};

foo()
  .done(function(){result.resolve()})
  .fail(function(){result.reject()})
;

setTimeout(function() {
    result.reject();
}, 50);

setTimeout(function(){
    console.log('Result is:', result.state());
}, 100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
i.Nemiro
  • 150
  • 6
  • 1
    This smells of [the deferred anti-pattern](http://stackoverflow.com/questions/23803743/what-is-the-deferred-antipattern-and-how-do-i-avoid-it). – Benjamin Gruenbaum May 06 '15 at 13:48
  • it's more complex. `foo` function can be not allowed for modify, and `result` can be resolved in many other ways. But if `foo` has been resolved the very first, `result` should have that resolution of the `foo`. – i.Nemiro May 07 '15 at 14:06

2 Answers2

2

You can use function passed in $.Deferred and resolve/reject deferred from inside:

var result = $.Deferred(function() {
    Math.random() > 0.5 ? this.resolve() : this.reject();
});

setTimeout(function(){
    document.write('Result is: ' + result.state());
}, 100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
dfsq
  • 191,768
  • 25
  • 236
  • 258
1

Your Deferred object def is superfluous (see the links given by Benajmin Gruenbaum why it's actually dangerous [silent fails]). Resolve/reject the result object:

var result = $.Deferred();
var foo = function() {
  return Math.random() > 0.5 ? result.resolve() : result.reject();
};

setTimeout(function(){
    document.write('Result is:', result.state());
}, 500);

foo();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
collapsar
  • 17,010
  • 4
  • 35
  • 61
  • 2
    This is called [the deferred anti-pattern](http://stackoverflow.com/questions/23803743/what-is-the-deferred-antipattern-and-how-do-i-avoid-it). – Benjamin Gruenbaum May 06 '15 at 13:48
  • @BenjaminGruenbaum Thanks for shedding light on an aspect of the code that was outside my focus. Answer adjusted. – collapsar May 06 '15 at 14:12
  • Resolving a `result` deferred that is defined outside of your `foo` function is actually even worse. – Bergi May 06 '15 at 17:08