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?
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(){});