Reputation: 5619
Please Note: This question was about why the jQuery implementation of promises does not follow the Promises/A+ specification with regards to requirement 2.2.4.
I have noticed that once a jQuery deferred object has been resolved, new calls to done will have any doneCallbacks called synchronously.
var d = $.Deferred();
d.resolve("Foo Bar!");
var fooBar = "Waiting";
d.done(function(data){fooBar = data; });
console.log(fooBar);//Will output "Foo Bar!" because the doneCallback is called synchronously
I had expected the callbacks to be put on the event queue (in which case the output to the console would have been "Waiting"), so as to match the behavior of calling done before the deferred object is resolved. Is my expectation unreasonable?
I couldn't seem to find any documentation around this behavior though, so I am unsure if this is a behavior I can rely on.
Upvotes: 4
Views: 481
Reputation: 11827
I think the issue you need to be concerned about here is "scope". This is assuming I am understanding your question here. You are curious why "Waiting" is not being set because is seemingly comes after your resolve.
For instance.. you have this snippet here:
var d = $.Deferred();
d.resolve("Foo Bar!");
var fooBar = "Waiting";
d.done(function(data){fooBar = data; });
console.log(fooBar)
What does that give?
Now we have this:
var d = $.Deferred();
var fooBar = "Waiting";
d.done(function(data){fooBar = data; });
console.log(fooBar)
d.resolve("Foo Bar!");
and this:
var d = $.Deferred();
d.done(function(data){fooBar = data; });
d.resolve("Foo Bar!");
var fooBar = "Waiting";
console.log(fooBar)
Now check this out!
var d = $.Deferred();
console.log( fooBar);
d.resolve("Foo Bar!");
var fooBar = "Waiting";
console.log( fooBar);
d.done(function(data){fooBar = data; });
console.log(fooBar)
Think about hoisting and scope.
Upvotes: 0
Reputation: 96
This behavior is documented explicitly here: http://api.jquery.com/jquery.deferred/
Once the object has entered the resolved or rejected state, it stays in that state. Callbacks can still be added to the resolved or rejected Deferred — they will execute immediately.
Upvotes: 2