How to get value from allowed jQuery.Deferred ()?

Here is my main 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 will not work if the deferred object is already allowed. 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 to get the value of jQuery.Deferred() already resolved?

+4
source share
2 answers

No, that’s exactly why the whole Deferred mechanism appeared. If you execute the "done" function after the asynchronous process is resolved, it will definitely be executed immediately.

From jQuery API docs:

If more functions are added by deferred .then () after Deferred resolves, they are called immediately with the arguments provided earlier.

This is also true for the ".done ()" functions.

+5
source

JavaScript in the 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 between the first line and the last line. β€œA few cycles later” means nothing in the land of JavaScript. Something will happen only with object.deferred after the function that performs the return.

+1
source

All Articles