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>

2
  • 1
    This smells of the deferred anti-pattern. Commented May 6, 2015 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. Commented May 7, 2015 at 14:06

2 Answers 2

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>

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

1 Comment

If we're being clever: var result = $.Deferred()[Math.random() > 0.5 ? "resolve" : "reject"]()
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>

3 Comments

@BenjaminGruenbaum Thanks for shedding light on an aspect of the code that was outside my focus. Answer adjusted.
Resolving a result deferred that is defined outside of your foo function is actually even worse.

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.