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");
Deferred() A factory function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
version added: 1.5deferred.The deferred. promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.
resolve( [args ] )Returns: Deferred. Description: Resolve a Deferred object and call any doneCallbacks with the given args .
A promise represents a value that is not yet known. This can better be understood as a proxy for a value not necessarily known when the promise is created. A deferred represents work that is not yet finished. A deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.
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
Would this do what you want?
var deferred = $.Deferred();
deferred.done(function(value) {
alert(value[0]);
}).done(function(value){
alert(value[1]);
});
deferred.resolve(["hello world", "goodbye, cruel world"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With