Reputation: 150
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>
Upvotes: 1
Views: 182
Reputation: 17238
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>
Upvotes: 1
Reputation: 193261
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>
Upvotes: 2