-1

Can someone simply explain the difference between promise and deferred in query?

I know what a promise is and when to use it, but I'm struggling to see what the difference is with deferred?

0

1 Answer 1

2

Promise is a read only view of the deferred object, it does not allow to resolve/reject the deferred but just allows to register handlers to the respective events.

When a method creates a deferred, you want that method to have control on when it has to be marked as rejected/resolved, if you return the deferred from that method then anybody can call resolve/reject on that deferred object, instead jQuery provides a read only view of the deferred called promise which can be created by called deferred.promise() which can be returned from the method which created the deferred so other methods can only register handlers for fail/success/always events but cannot change the state of the deferred.

function create(){ var d = $.Deferred(); ..... //we can call resolve/reject using d return d.promise(); } var promise = create(); //we cannot call resolve/reject on this object promise.done(function(){}); 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, could you elaborate on the resolve/reject, why would one use this?
@panthro they're used to... resolve, or, reject the deferred.. when it is resolved, done callbacks and always callback get executed and the deferred can no longer be resolved or rejected.
So, if I just used deferred, I could decide what makes it reject etc? Promise means it can;t be interfered with?
@panthro - Exactly. You hand off a promise to any code that you don't want to have the authority to decide whether to resolve or reject the deferred. It's a little like the distinction between private and public methods.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.