Tuesday, 23 May 2017

What is $.Deferred() and .resolve in jquery



What exactly .deferred do what is its work and where and when we should use .deferred with resolve. In below function I have two .done callbacks. I want to set two different callback msg. fiddle



var deferred = $.Deferred();
deferred.done(function(value) {
alert(value);
}).done(function(id){
alert(id)
});

console.log(deferred)

deferred.resolve("hello world");

Answer



jQuery.Deferred is the main tool of jQuery's implementation of the promise pattern.



Here are a few links, worth reading :





As for your specific need : you should use .then() (read the docs for .done() and .then()).



var deferred = $.Deferred();

deferred.then(function(value) {
alert(value);
return 42;
}).then(function(id){
alert('The answer : ' + id);
});

console.log(deferred)

deferred.resolve("hello world");


fiddle


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...