0

I was looking an example of $.deferred. In that example they use .promise, I really dont understand it role over there because I am getting the same result without it, So I want to know In which it is necessary to use .promise or how can we justify .promise in given example.

If I just use return deferred, Its works fine as well.

function waitforms(ms){
var deferred= $.Deferred();
setTimeout(function(){
deferred.resolve(new Date())
},ms)

return deferred.promise();  // working with return deferred also
}

waitfor(2000).done(function(date){
console.log('Contrived example finished at'+ date.getTime())
})
Moppo
  • 18,797
  • 5
  • 65
  • 64
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • 1
    https://api.jquery.com/deferred.promise/ - seems to explain in nicely – user2864740 Jul 19 '15 at 07:55
  • Why the heck someone would down vote this question? Please put an effort to post in posting explanation as well when you are giving any question a thumbs down. +1 to question from my side. – anuj_io Jul 19 '15 at 08:19

1 Answers1

1

A promise is a protected and more limited subset of a deferred.

With a deferred, you can resolve or reject the promise in addition to all the normal methods such as .then().

With a promise, you still have all the normal methods like .then() for monitoring the state of the promise, but you cannot resolve or reject it.

So, a promise is used for letting people monitor an operation, but not actually trigger it. You should get the promise and return it to others when that's all they should be able to do (monitor it). You can let people have access to the deferred object if they should be able to actually cause a resolve or reject on it.

Usually, only the promise should go to the outside world and the deferred should be kept internal to the operation itself.

jfriend00
  • 683,504
  • 96
  • 985
  • 979