Detailed explanation of jQuery's Deferred object
deferredObject is the jQuery interface to Promises implementation. It is a general interface for asynchronous operations. It can be regarded as a task waiting to be completed. Developers set it through some interfaces. In fact, it plays the role of proxy. Wrap those asynchronous operations into objects with certain unified characteristics. Typical examples are Ajax operations, web page animations , web workers, etc. All Ajax operations
functions of jQuery., by default returns a deferred object.
What are Promises? It takes a long time, and other operations must be queued to wait. In order to avoid the entire program becoming unresponsive, the usual solution is to write those operations in the form of "callback function " (callback) like this. Although it can solve the problem, it has some significant shortcomings:
1. Callback functions are often written in the form offunction parameters, which causes the input and output of the function to be very confusing and the entire program cannot be read. Poor performance; 2. Only one callback function can often be specified. If there are multiple operations, the callback function needs to be rewritten. 3. The entire program's running process is disrupted, debugging and debuggingThe difficulty increases accordingly.
Promises were proposed to solve these problems. Its main purpose is to replace callback functions and become a solution for asynchronous operations. Its core idea is to allow asynchronous operations to return. An object, other operations are completed against this object. For example, assume that the ajax operation returns a Promise object. The code is as follows:
Then, the Promise object has a then. Method can be used to specify a callback function. Once the asynchronous operation is completed, the specified callback function is called. The code is as follows:
The code is as follows:
var promise = get('http://www.example.com');
promise.then(function (content) { console.log(content) })
$.deferred() method
get('http://www.example.com').then(function (content) { console.log(content) })
done() and fail()
$.ajax({ url:"/echo/json/", success: function(response) { console.info(response.name); } });
Both methods are used Bind callback function. done() specifies the callback function after the asynchronous operation succeeds, and fail() specifies the callback function after the failure.
$.ajax({ url: "/echo/json/", }).then(function (response) { console.info(response.name); });
They return the original deferred object, so you can use chain writing, and then link other methods (including done and fail) within).
resolve() and reject()
are used to change thestate
of the deferred object. resolve() changes the status to asynchronous operation success, and reject() changes the status to operation failure.
var deferred = $.deferred();
Once resolve() is called, the callback functions specified by the done() and then() methods will be executed in sequence; once reject is called (), the callback functions specified by the fail() and then() methods will be executed in sequence.
state method
This method is used to return the current state of the deferred object.
var deferred = $.Deferred(); deferred.done(function(value) { alert(value); });
The code is as follows:
This method has three return values:
progress() is used to specify a callback function, which will be executed when the notify() method is called. Its purpose is to provide an interface so that certain operations can be performed during the execution of asynchronous operations, such as regularly returning the progress of the
progress barvar deferred = $.Deferred(); deferred.done(function(value) { alert(value); }); deferred.resolve("hello world");
then()
var deferred = new $.Deferred(); deferred.state(); // "pending"deferred.resolve(); deferred.state(); // "resolved"
deferred.then( doneFilter [, failFilter ] [, progressFilter ] )
在jQuery 1.8之前,then()只是.done().fail()写法的语法糖,两种写法是等价的。在jQuery 1.8之后,then()返回一个新的deferred对象,而done()返回的是原有的deferred对象。如果then()指定的回调函数有返回值,该返回值会作为参数,传入后面的回调函数。
代码如下:
var defer = jQuery.Deferred(); defer.done(function(a,b){ return a * b; }).done(function( result ) { console.log("result = " + result); }).then(function( a, b ) { return a * b; }).done(function( result ) { console.log("result = " + result); }).then(function( a, b ) { return a * b; }).done(function( result ) { console.log("result = " + result); }); defer.resolve( 2, 3 );
在jQuery 1.8版本之前,上面代码的结果是:
代码如下:
result = 2 result = 2 result = 2
在jQuery 1.8版本之后,返回结果是
代码如下:
result = 2 result = 6 result = NaN
这一点需要特别引起注意。
代码如下:
$.ajax( url1, { dataType: "json" } ) .then(function( data ) { return $.ajax( url2, { data: { user: data.userId } } ); }).done(function( data ) { // 从url2获取的数据 });
上面代码最后那个done方法,处理的是从url2获取的数据,而不是从url1获取的数据。
利用then()会修改返回值这个特性,我们可以在调用其他回调函数之前,对前一步操作返回的值进行处理。
代码如下:
var post = $.post("/echo/json/") .then(function(p){ return p.firstName; }); post.done(function(r){ console.log(r); });
上面代码先使用then()方法,从返回的数据中取出所需要的字段(firstName),所以后面的操作就可以只处理这个字段了。
有时,Ajax操作返回json字符串里面有一个error属性,表示发生错误。这个时候,传统的方法只能是通过done()来判断是否发生错误。通过then()方法,可以让deferred对象调用fail()方法。
代码如下:
var myDeferred = $.post('/echo/json/', {json:JSON.stringify({'error':true})}) .then(function (response) { if (response.error) { return $.Deferred().reject(response); } return response; },function () { return $.Deferred().reject({error:true}); } ); myDeferred.done(function (response) { $("#status").html("Success!"); }).fail(function (response) { $("#status").html("An error occurred"); });
always()
always()也是指定回调函数,不管是resolve或reject都要调用。
pipe方法
pipe方法接受一个函数作为参数,表示在调用then方法、done方法、fail方法、always方法指定的回调函数之前,先运行pipe方法指定的回调函数。它通常用来对服务器返回的数据做初步处理。
promise对象
大多数情况下,我们不想让用户从外部更改deferred对象的状态。这时,你可以在deferred对象的基础上,返回一个针对它的promise对象。我们可以把后者理解成,promise是deferred的只读版,或者更通俗地理解成promise是一个对将要完成的任务的承诺。
你可以通过promise对象,为原始的deferred对象添加回调函数,查询它的状态,但是无法改变它的状态,也就是说promise对象不允许你调用resolve和reject方法。
代码如下:
function getPromise(){ return $.Deferred().promise(); } try{ getPromise().resolve("a"); } catch(err) { console.log(err); }
上面的代码会出错,显示TypeError {} 。
jQuery的ajax() 方法返回的就是一个promise对象。此外,Animation类操作也可以使用promise对象。
代码如下:
var promise = $('p.alert').fadeIn().promise();
$.when()方法
$.when()接受多个deferred对象作为参数,当它们全部运行成功后,才调用resolved状态的回调函数,但只要其中有一个失败,就调用rejected状态的回调函数。它相当于将多个非同步操作,合并成一个。
代码如下:
$.when( $.ajax( "/main.php" ), $.ajax( "/modules.php" ), $.ajax( "/lists.php" ) ).then(successFunc, failureFunc);
上面代码表示,要等到三个ajax操作都结束以后,才执行then方法指定的回调函数。
when方法里面要执行多少个操作,回调函数就有多少个参数,对应前面每一个操作的返回结果。
代码如下:
$.when( $.ajax( "/main.php" ), $.ajax( "/modules.php" ), $.ajax( "/lists.php" ) ).then(function (resp1, resp2, resp3){ console.log(resp1); console.log(resp2); console.log(resp3); });
上面代码的回调函数有三个参数,resp1、resp2和resp3,依次对应前面三个ajax操作的返回结果。
when方法的另一个作用是,如果它的参数返回的不是一个Deferred或Promise对象,那么when方法的回调函数将 立即运行。
代码如下:
$.when({testing: 123}).done(function (x){ console.log(x.testing); // "123" });
上面代码中指定的回调函数,将在when方法后面立即运行。
利用这个特点,我们可以写一个具有缓存效果的异步操作函数。也就是说,第一次调用这个函数的时候,将执行异步操作,后面再调用这个函数,将会返回缓存的结果。
代码如下:
function maybeAsync( num ) { var dfd = $.Deferred(); if ( num === 1 ) { setTimeout(function() { dfd.resolve( num ); }, 100); return dfd.promise(); } return num;}$.when(maybeAsync(1)).then(function (resp){ $('#target').append(' ' + resp + ' ');}); $.when(maybeAsync(0)).then(function (resp){ $('#target').append( ' ' + resp + ' ');});
上面代码表示,如果maybeAsync函数的参数为1,则执行异步操作,否则立即返回缓存的结果。
实例
wait方法
我们可以用deferred对象写一个wait方法,表示等待多少毫秒后再执行。
代码如下:
$.wait = function(time) { return $.Deferred(function(dfd) { setTimeout(dfd.resolve, time); }); }
使用方法如下:
代码如下:
$.wait(5000).then(function() { alert("Hello from the future!"); });
改写setTimeout方法
在上面的wait方法的基础上,还可以改写setTimeout方法,让其返回一个deferred对象。
代码如下:
function doSomethingLater(fn, time) { var dfd = $.Deferred(); setTimeout(function() { dfd.resolve(fn()); }, time || 0); return dfd.promise(); } var promise = doSomethingLater(function (){ console.log( '已经延迟执行' ); }, 100);
自定义操作使用deferred接口
我们可以利用deferred接口,使得任意操作都可以用done()和fail()指定回调函数。
代码如下:
Twitter = { search:function(query) { var dfr = $.Deferred(); $.ajax({ url:"http://search.twitter.com/search.json", data:{q:query}, dataType:'jsonp', success:dfr.resolve }); return dfr.promise(); } }
使用方法如下:
代码如下:
Twitter.search('intridea').then(function(data) { alert(data.results[0].text);});
deferred对象的另一个优势是可以附加多个回调函数。
代码如下:
function doSomething(arg) { var dfr = $.Deferred(); setTimeout(function() { dfr.reject("Sorry, something went wrong."); }); return dfr; } doSomething("uh oh").done(function() { alert("Won't happen, we're erroring here!"); }).fail(function(message) { alert(message) });
以上就是jQuery之Deferred对象详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute
