Home >Web Front-end >JS Tutorial >Detailed explanation of jQuery's Deferred object

Detailed explanation of jQuery's Deferred object

PHP中文网
PHP中文网Original
2017-03-30 15:12:321360browse

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 of

function 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:

can combine the above two. The code snippets are combined so that the flow of the program can be seen more clearly. >


The code is as follows:

After version 1.7, Ajax operations directly return Promise objects, which means that the callback function can be specified using the then method. The code is as follows:
var promise = get('http://www.example.com');


Deferred object method

promise.then(function (content) {
  console.log(content)
})

$.deferred() method

is used to generate a deferred object.

get('http://www.example.com').then(function (content) {
  console.log(content)
})
The code is as follows:


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.

The code is as follows:
$.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 the

state
of the deferred object. resolve() changes the status to asynchronous operation success, and reject() changes the status to operation failure.

The code is as follows:
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:

notify() and progress( )

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 bar
var deferred = $.Deferred();
deferred.done(function(value) {
   alert(value);
});
deferred.resolve("hello world");
.


The code is as follows:

then()


then() is also used to specify the callback function, which can accept three parameters, that is, three callback functions. The first parameter is the callback function called when resolve, the second parameter is the callback function called when reject, and the third parameter is the callback function called by the progress() method.

var deferred = new $.Deferred();
deferred.state();  // "pending"deferred.resolve();
deferred.state();  // "resolved"
The code is as follows:

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)!


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