jQuery.Deferred() detailed explanation

Guanhui
Release: 2020-05-06 10:01:25
forward
2768 people have browsed it

1. What is a deferred object?

In the process of developing websites, we often encounter certain JavaScript operations that take a long time. Among them, there are both asynchronous operations (such as ajax reading server data) and synchronous operations (such as traversing a large array), and the results are not available immediately.

The usual approach is to specify a callback function (callback) for them. That is, specify in advance which functions should be called once they have finished running.

However, jQuery is very weak in terms of callback functions. In order to change this, the jQuery development team designed the deferred object.

Simply put, 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.

It solves the problem of how to handle time-consuming operations, provides better control over those operations, and a unified programming interface. Its main functions can be summarized into four points. Below we will learn step by step through sample code.

2. Chain writing method of ajax operation

First, review the traditional writing method of jQuery's ajax operation:

  $.ajax({     url: "test.html",     success: function(){       alert("哈哈,成功了!");     },     error:function(){       alert("出错啦!");     }   });
Copy after login

(Run code example 1 )

In the above code, $.ajax() accepts an object parameter. This object contains two methods: the success method specifies the callback function after the operation is successful, and the error method specifies the callback function after the operation fails.

After the $.ajax() operation is completed, if you are using a jQuery version lower than 1.5.0, the XHR object will be returned, and you cannot perform chain operations; if it is higher than 1.5.0, What is returned is a deferred object, which can be chained.

Now, the new way of writing is like this:

  $.ajax("test.html")   .done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); });
Copy after login

(Run code example 2)

As you can see, done() is equivalent to the success method, and fail() is equivalent to in the error method. After adopting the chain writing method, the readability of the code is greatly improved.

3. Specify multiple callback functions for the same operation

One of the great benefits of the deferred object is that it allows you to add multiple callback functions freely.

Still taking the above code as an example, if after the ajax operation is successful, in addition to the original callback function, I also want to run another callback function, what should I do?

It’s very simple, just add it at the end.

  $.ajax("test.html")   .done(function(){ alert("哈哈,成功了!");} )   .fail(function(){ alert("出错啦!"); } )   .done(function(){ alert("第二个回调函数!");} );
Copy after login

(Run code example 3)

You can add as many callback functions as you like, and they are executed in the order they are added.

4. Specify callback functions for multiple operations

Another great benefit of the deferred object is that it allows you to specify a callback function for multiple events. This is This cannot be done with traditional writing.

Please look at the following code, which uses a new method $.when():

  $.when($.ajax("test1.html"), $.ajax("test2.html"))   .done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); });
Copy after login

(Run code example 4)

The meaning of this code is , first perform two operations $.ajax("test1.html") and $.ajax("test2.html"). If both succeed, run the callback function specified by done(); if one fails or both fail , execute the callback function specified by fail().

5. Callback function interface for common operations (Part 1)

The biggest advantage of the deferred object is that it combines this set of callback function interfaces from ajax Operations are extended to all operations. In other words, any operation - whether it is an ajax operation or a local operation, whether it is an asynchronous operation or a synchronous operation - can use various methods of the deferred object to specify a callback function.

Let’s look at a specific example. Suppose there is a time-consuming operation wait:

  var wait = function(){     var tasks = function(){       alert("执行完毕!");     };     setTimeout(tasks,5000);   };
Copy after login

We specify a callback function for it, what should we do?

Naturally, you will think that you can use $.when():

  $.when(wait())   .done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); });
Copy after login

(Run code example 5)

However, if you write it like this, done() The method will be executed immediately and will not function as a callback function. The reason is that the parameters of $.when() can only be deferred objects, so wait() must be rewritten:

  var dtd = $.Deferred(); // 新建一个deferred对象   var wait = function(dtd){     var tasks = function(){       alert("执行完毕!");       dtd.resolve(); // 改变deferred对象的执行状态     };     setTimeout(tasks,5000);     return dtd;   };
Copy after login

Now, the wait() function returns a deferred object, which can be chained Operated.

  $.when(wait(dtd))   .done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); });
Copy after login

(Run code example 6)

After the wait() function is run, the callback function specified by the done() method will automatically run.

6. deferred.resolve() method and deferred.reject() method

If you look carefully, you will find that in the above wait() function, there are There is one place I didn't explain. That's what dtd.resolve() does?

To clarify this issue, we need to introduce a new concept "execution status". jQuery stipulates that deferred objects have three execution states - unfinished, completed and failed. If the execution status is "completed" (resolved), the deferred object immediately calls the callback function specified by the done() method; if the execution status is "failed", the callback function specified by the fail() method is called; if the execution status is "unsuccessful" Completed", continue to wait, or call the callback function specified by the progress() method (added in jQuery 1.7 version).

前面部分的ajax操作时,deferred对象会根据返回结果,自动改变自身的执行状态;但是,在wait()函数中,这个执行状态必须由程序员手动指定。dtd.resolve()的意思是,将dtd对象的执行状态从"未完成"改为"已完成",从而触发done()方法。

类似的,还存在一个deferred.reject()方法,作用是将dtd对象的执行状态从"未完成"改为"已失败",从而触发fail()方法。

  var dtd = $.Deferred(); // 新建一个Deferred对象   var wait = function(dtd){     var tasks = function(){       alert("执行完毕!");       dtd.reject(); // 改变Deferred对象的执行状态     };     setTimeout(tasks,5000);     return dtd;   };   $.when(wait(dtd))   .done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); });
Copy after login

(运行代码示例7)

七、deferred.promise()方法

上面这种写法,还是有问题。那就是dtd是一个全局对象,所以它的执行状态可以从外部改变。

请看下面的代码:

  var dtd = $.Deferred(); // 新建一个Deferred对象   var wait = function(dtd){     var tasks = function(){       alert("执行完毕!");       dtd.resolve(); // 改变Deferred对象的执行状态     };     setTimeout(tasks,5000);     return dtd;   };   $.when(wait(dtd))   .done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); });   dtd.resolve();
Copy after login

(运行代码示例8)

我在代码的尾部加了一行dtd.resolve(),这就改变了dtd对象的执行状态,因此导致done()方法立刻执行,跳出"哈哈,成功了!"的提示框,等5秒之后再跳出"执行完毕!"的提示框。

为了避免这种情况,jQuery提供了deferred.promise()方法。它的作用是,在原来的deferred对象上返回另一个deferred对象,后者只开放与改变执行状态无关的方法(比如done()方法和fail()方法),屏蔽与改变执行状态有关的方法(比如resolve()方法和reject()方法),从而使得执行状态不能被改变。

请看下面的代码:

  var dtd = $.Deferred(); // 新建一个Deferred对象   var wait = function(dtd){     var tasks = function(){       alert("执行完毕!");       dtd.resolve(); // 改变Deferred对象的执行状态     };     setTimeout(tasks,5000);     return dtd.promise(); // 返回promise对象   };   var d = wait(dtd); // 新建一个d对象,改为对这个对象进行操作   $.when(d)   .done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); });   d.resolve(); // 此时,这个语句是无效的
Copy after login

(运行代码示例9)

在上面的这段代码中,wait()函数返回的是promise对象。然后,我们把回调函数绑定在这个对象上面,而不是原来的deferred对象上面。这样的好处是,无法改变这个对象的执行状态,要想改变执行状态,只能操作原来的deferred对象。

不过,更好的写法是allenm所指出的,将dtd对象变成wait()函数的内部对象。

  var wait = function(dtd){     var dtd = $.Deferred(); //在函数内部,新建一个Deferred对象     var tasks = function(){       alert("执行完毕!");       dtd.resolve(); // 改变Deferred对象的执行状态     };     setTimeout(tasks,5000);     return dtd.promise(); // 返回promise对象   };   $.when(wait())   .done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); });
Copy after login

(运行代码示例10)

八、普通操作的回调函数接口(中)

另一种防止执行状态被外部改变的方法,是使用deferred对象的建构函数$.Deferred()。

这时,wait函数还是保持不变,我们直接把它传入$.Deferred():

  $.Deferred(wait)   .done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); });
Copy after login

(运行代码示例11)

jQuery规定,$.Deferred()可以接受一个函数名(注意,是函数名)作为参数,$.Deferred()所生成的deferred对象将作为这个函数的默认参数。

九、普通操作的回调函数接口(下)

除了上面两种方法以外,我们还可以直接在wait对象上部署deferred接口。

  var dtd = $.Deferred(); // 生成Deferred对象   var wait = function(dtd){     var tasks = function(){       alert("执行完毕!");       dtd.resolve(); // 改变Deferred对象的执行状态     };     setTimeout(tasks,5000);   };   dtd.promise(wait);   wait.done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); });   wait(dtd);
Copy after login

(运行代码示例12)

这里的关键是dtd.promise(wait)这一行,它的作用就是在wait对象上部署Deferred接口。正是因为有了这一行,后面才能直接在wait上面调用done()和fail()。

十、小结:deferred对象的方法

前面已经讲到了deferred对象的多种方法,下面做一个总结:

  (1) $.Deferred() 生成一个deferred对象。

  (2) deferred.done() 指定操作成功时的回调函数

  (3) deferred.fail() 指定操作失败时的回调函数

  (4) deferred.promise() 没有参数时,返回一个新的deferred对象,该对象的运行状态无法被改变;接受参数时,作用为在参数对象上部署deferred接口。

  (5) deferred.resolve() 手动改变deferred对象的运行状态为"已完成",从而立即触发done()方法。

  (6)deferred.reject() 这个方法与deferred.resolve()正好相反,调用后将deferred对象的运行状态变为"已失败",从而立即触发fail()方法。

  (7) $.when() 为多个操作指定回调函数。

除了这些方法以外,deferred对象还有二个重要方法,上面的教程中没有涉及到。

  (8)deferred.then()

有时为了省事,可以把done()和fail()合在一起写,这就是then()方法。

  $.when($.ajax( "/main.php" ))   .then(successFunc, failureFunc );
Copy after login

如果then()有两个参数,那么第一个参数是done()方法的回调函数,第二个参数是fail()方法的回调方法。如果then()只有一个参数,那么等同于done()。

  (9)deferred.always()

这个方法也是用来指定回调函数的,它的作用是,不管调用的是deferred.resolve()还是deferred.reject(),最后总是执行。

  $.ajax( "test.html" )   .always( function() { alert("已执行!");} );
Copy after login

The above is the detailed content of jQuery.Deferred() detailed explanation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!