Home  >  Article  >  Web Front-end  >  Introduction to the usage of deferred objects in jquery (with examples)

Introduction to the usage of deferred objects in jquery (with examples)

不言
不言forward
2019-03-27 09:20:052017browse

This article brings you an introduction to the usage of deferred objects in jquery (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What is a deferred object?

Deferred objects, introduced in jQuery 1.5, create a chainable tool object by calling the jQuery.Deferred() method. It can register multiple callbacks to the callback queue, call the callback queue, and prepare to replace the success or failure status of any synchronous or asynchronous function. ——jQuery API Chinese Documentation 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. ——Ruan Yifeng

The main function of deferred object

Chain writing method of ajax operation

$.ajax("test.html")
   .done(function(){ alert("success"); })
   .fail(function(){ alert("error"); });

$.ajax() After the operation is completed, if If you are using a version of jQuery lower than 1.5.0, an XHR object is returned and chaining operations cannot be performed; if it is a version higher than 1.5.0, a deferred object is returned and chaining operations are possible. As you can see, done() is equivalent to the success method, and fail() is equivalent to the error method. After adopting the chain writing method, the readability of the code is greatly improved.

Here we emphasize the jqXHR object. Starting from jQuery 1.5, the jqXHR object returned by $.ajax() itself is a deferred object, so it can be called in a chain like in the above code.

Starting from jQuery 1.5, the jqXHR object returned by $.ajax() implements the Promise interface, so that it has all the properties, methods and behaviors of Promise. (See Deferred object for more information). In order to make the name of the callback function unified and easy to use in $.ajax(). jqXHR also provides .error() .success() and .complete() methods. These methods all take a parameter, which is a function. This function is called at the end of the $.ajax() request, and the parameters received by this function are consistent with the parameters when the $.ajax() function is called. This will allow you to assign to multiple callback functions on a single request, and even allow you to assign to callback functions after the request has completed (if the request has completed, the callback function will be called immediately).

Note: jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated starting from jQuery 1.8 and removed starting from jQuery 3.0. You can use jqXHR.done (), jqXHR.fail(), and jqXHR.always() instead.

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. 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('success'); })
   .fail(function(){ alert('error'); })
    .done(function(){ alert('第二个回调函数!'); });

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

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, which is not possible with traditional writing. of.

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

$.when($.ajax("test1.html"), $.ajax("test2.html"))
   .done(function(){ alert('success'); })
   .fail(function(){ alert('error'); });

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

$.when() Please refer to the documentation for details on how to use the method.

Callback function interface for common operations
The biggest advantage of the deferred object is that it extends this set of callback function interfaces from ajax operations 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, specifying a callback function for a time-consuming operation 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('success'); })
    .fail(function () { alert('error'); });

Another approach is to directly pass the wait function into $.Deferred ():

$.Deferred(wait)
   .done(function(){ alert('success'); })
   .fail(function(){ alert('error'); });

jQuery stipulates that $.Deferred() can accept a function name (note, it is a function name) as a parameter, $.Deferred() The generated deferred object will be used as the default parameter of this function.

For more specific information, please see Ruan Yifeng’s documentation.

Methods of deferred objects

$.Deferred() generates a deferred object.
jQuery.Deferred([beforeStart]) The factory function creates a new deferred object.

Description: A factory function that returns a chained utility object. Use the return object method to register multiple callbacks in the callback queue, call the callback queue, and pass the success or failure status of any synchronous or asynchronous function. .

beforeStart: Type Function(Deferred deferred), a constructor that returns the previously called function.

jQuery.Deferred 方法可以传递一个可选的函数, 这个函数在方法返回之前调用,并且会把新的 deferred(延迟)对象作为 this 对象,将其作为第一个参数传递给函数。例如,被调用的函数可以使用 deferred.then() 绑定回调。

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

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

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

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

一个 Deferred(延迟)对象开始于 pending 状态。 任何回调使用 deferred.then(), deferred.always(), deferred.done(), 或者 deferred.fail() 添加到这个对象都是排队等待执行。调用 deferred.resolve() 转换 Deferred(递延)到 resolved(解决)的状态,并立即执行设置中任何的 doneCallbacks。调用 deferred.reject() 转换 Deferred(递延)到 rejected(拒绝)的状态,并立即执行设置中任何的 failCallbacks。一旦对象已经进入了解决或拒绝状态,它处于该状态。回调仍然可以添加到解决或拒绝 Deferred(递延)- 他们会立即执行。

$.ajax() 返回的 jqXHR 对象 会根据请求返回的结果,自动改变自身的执行状态。但是,对于其他通过 $.Deferred() 方法生成的 deferred 对象,它们的执行状态必须由程序员手动指定,由代码决定在什么时候触发回调函数。

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

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

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

$.when($.ajax( '/main.php' ))
   .then(successFunc, failureFunc);

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

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

$.ajax( 'test.html' )
    .always( function() { alert('已执行!');} );

更多信息请参见 jQuery API中文文档。

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!

The above is the detailed content of Introduction to the usage of deferred objects in jquery (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete