Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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");
like image 721
Jitender Avatar asked Oct 02 '13 06:10

Jitender


People also ask

What is deferred () in JQuery?

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.

What is deferred and promise in JQuery?

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.

What does deferred resolve () return?

resolve( [args ] )Returns: Deferred. Description: Resolve a Deferred object and call any doneCallbacks with the given args .

What is the difference between a deferred and a promise?

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.


2 Answers

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

Here are a few links, worth reading :

  • [SO] Implement promises pattern
  • [jQuery doc] Deferred
  • [wikipedia] Futures and Promises

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

like image 197
LeGEC Avatar answered Oct 04 '22 09:10

LeGEC


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"]);
like image 29
Michael Lorton Avatar answered Oct 04 '22 09:10

Michael Lorton