Can I rely on the synchronous nature of allowed pending jquery objects

Please note: This question was about why the jQuery promises implementation does not meet the Promises / A + specification with respect to 2.2.4 .


I noticed that after resolving the pending jQuery object, new calls done will have any calls made that are 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 expected callbacks to be placed in the event queue (in this case, the output to the console would be โ€œWaitingโ€) to match the behavior of the call made before the deferred object is resolved. Is my expectation unfounded?

It seems I could not find any documentation on this behavior, so I'm not sure if this is a behavior I can rely on.

+4
source share
2 answers

This behavior is explicitly described here: http://api.jquery.com/jquery.deferred/

Once an object has entered an allowed or rejected state, it remains in that state. Callbacks can be added to allowed or rejected Deferred - they will be executed immediately.

+3
source

I think the problem you should worry about is the "area". This suggests that I understand your question here. You are curious why the โ€œWaitโ€ is not set, because it seems to come after your decision.

For example, 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 it 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 it 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 the climb and the area .

0
source

All Articles