Home  >  Article  >  Web Front-end  >  The difference between Deferred and promise in jQuery_jquery

The difference between Deferred and promise in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 15:06:391129browse

What is the difference between Deferred and Promise?

promise

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

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

The benefits of using Promises are as follows:

You can call the done() and fail() functions multiple times and use different callback functions. Maybe you have one callback function to stop the animation, one to initiate a new AJAX request, and one to display 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 is completed, you can still call the done() and fail() functions, and the callback function can be executed immediately. There is no confusion of variables between different states. When an AJAX call ends, it maintains a success or failure status and this status does 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) { // 处理两个XHR对象 });

deferred

To put it simply, the deferred object is jQuery’s callback function solution. In English, defer means "delay", so the meaning of a deferred object is to "delay" execution until a certain point in the future.

A deferred object can do the same 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 execute functions related to done(). The reject() function is used to handle failed results and execute functions related to fail().

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

Summary

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn