What's the difference between deferred and promise?
Promise
A promise is an object that is returned by an asynchronous function. When you want to write one of these functions yourself, you need to use a deferred.
var promise = $.ajax ({
URL: "/myserverscript"
});
Promise.done (mysuccessfunction);
Promise.fail (myerrorfunction);
var promise = $.ajax ({
URL: "/myserverscript"
});
The benefits of using promises have the following points:
You can call the done () and fail () functions multiple times and use different callback functions. Perhaps one of your callback functions is used to stop the animation, one to launch a new AJAX request, and one to present the received data to the user.
var promise = $.ajax ({url: "/myserverscript"});
Promise.done (mystopanimationfunction); Promise.done (myotherajaxfunction);
Promise.done (myshowinfofunction); Promise.fail (myerrorfunction);
Even after the Ajax call completes, you can still invoke the done () and fail () functions, and the callback function can be executed immediately. Variable chaos does not occur between different states. When an Ajax call ends, it maintains a state of success or failure, and this state does not change.
You can combine promises. Sometimes you need to make two AJAX requests at the same time and want to call a function when all two AJAX requests succeed. To complete 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) {//Processing two XHR objects});
Deferred
Simply put, the deferred object is the callback function solution for jquery. In English, defer means "delay", so the meaning of the deferred object is "delay" to a certain point in the future.
A deferred object can do almost as much as a promise object, but it has two functions to trigger the done () and fail () functions.
A deferred object has a resolve () function to handle a successful result and perform a function related to the done (). The Reject () function is used to process failed results and perform functions related to fail ().
You can provide parameters for both the resolve () and The Reject () functions, and they will all be passed to the callback function associated with the done () and fail ().
Summarize
JQuery Ajax is the return of a Promise object, which contains the done (), fail () method, deferred is the implementation of the process to return the Promise object.