Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()?

like image 693
benekastah Avatar asked Oct 19 '11 15:10

benekastah


2 Answers

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.

like image 149
Pointy Avatar answered Oct 17 '22 20:10

Pointy


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.

like image 22
Skilldrick Avatar answered Oct 17 '22 21:10

Skilldrick