Here is my basic situation:
function somePostThing() {
return $post("/someUrl").done(doSomething);
}
function doSomething(data) {
// do stuff with the data
}
var object = {};
object.deferred = somePostThing();
// A few cycles later, object.deferred may be resolved or unresolved
object.deferred.done(function () { /* ... */ });
The last line may or may not work, because done
won't fire in the event that the deferred object is already resolved. I would like to be able to do something like this:
function doSomethingWithData(data) {
// do stuff
}
var value;
if (object.deferred.isResolved()) doSomethingWithData(object.deferred.value());
else object.deferred.done(doSomethingWithData);
How do I get the value of an already resolved jQuery.Deferred()
?
No, that's actually exactly why the whole "Deferred" mechanism came into being. If you pass in a "done" function after the asynchronous process has been resolved, it most definitely will be executed immediately.
From the jQuery API docs:
If more functions are added by deferred.then() after the Deferred is resolved, they are called immediately with the arguments previously provided.
That's true for the ".done()" functions also.
JavaScript in a browser is single threaded. So, in the following code snippet:
object.deferred = somePostThing();
// Nothing can happen to object.deferred here
object.deferred.done(function () { /* ... */ });
nothing will happen in between the first line and the last line. "A few cycles later" doesn't mean anything in JavaScript-land. Something will only happen to object.deferred
after the function that is executing returns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With