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

panthro
  • 22,779
  • 66
  • 183
  • 324

1 Answers1

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(){});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Thanks, could you elaborate on the resolve/reject, why would one use this? – panthro Nov 12 '13 at 16:12
  • @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. – Kevin B Nov 12 '13 at 16:12
  • So, if I just used deferred, I could decide what makes it reject etc? Promise means it can;t be interfered with? – panthro Nov 12 '13 at 16:26
  • 1
    @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. – Ken Smith Nov 12 '13 at 16:38