SoFunction
Updated on 2025-04-10

The difference between Deferred and promise in jQuery

What is the difference between Deferred and Promise?

promise

A promise is an object returned by an asynchronous function. When you want to write a function like this yourself, you need to use a deferred.

var promise = $.ajax({
url: "/myServerScript"
});
(mySuccessFunction); 
(myErrorFunction); 
var promise = $.ajax({
url: "/myServerScript"
}); 
(mySuccessFunction,myErrorFunction); 

The benefits of using Promises are as follows:

You can call done() and fail() functions multiple times and use different callback functions. Perhaps one of your callbacks is used to stop the animation, one is used to initiate a new AJAX request, and one is used to display the received data to the user.

var promise = $.ajax({ url: "/myServerScript" });
(myStopAnimationFunction); (myOtherAjaxFunction); 
(myShowInfoFunction); (myErrorFunction);

Even after the AJAX call is completed, you can still call the done() and fail() functions, and the callback function can be executed immediately. There is no variable confusion between different states. When an AJAX call ends, it maintains a successful state or a failed state, and this state will not change.

You can merge promises. Sometimes you need to make two AJAX requests at the same time and want to call a function when both AJAX requests are successful. To accomplish this task, you need to use a new $.when() function:

var promise1 = $.ajax("/myServerScript1"); 
var promise2 = $.ajax("/myServerScript2");
$.when(promise1, promise2).done(function(xhrObject1, xhrObject2) { // Handle twoXHRObject });

deferred

Simply put, the deferred object is the jQuery callback function solution. In English, defer means "delay", so the meaning of deferred object is "delay" to be executed at a certain point in the future.

A deferred object can do something similar to a promise object, but it has two functions to trigger the done() and fail() functions.

A deferred object has a resolve() function to process a successful result and execute a function related to done(). The reject() function is used to process the failed result and execute the functions related to fail().

You can provide parameters to both resolve() and reject() functions, and they will be passed to the callback function related to done() and fail().

Summarize

jQuery's ajax returns a promise object, which contains done() and fail() methods; deferred is the process of returning this promise object.