Home Web Front-end JS Tutorial jquery deferred object use case

jquery deferred object use case

Apr 23, 2018 pm 03:53 PM
jquery use Case

This time I will bring you a jquery delayed object usage case. What are the precautions for using jquery delayed object. The following is a practical case, let’s take a look.

The technical level is generally limited. If there are any mistakes, please correct me.

ES6 has implemented delayed object Promise, but today’s protagonist is the delayed object in JQ, and the routines are actually the same. Let's take a look at a far-fetched example:

<button id="add">add</button><button id="remove">remove</button>
<p id="content"></p>
Copy after login
$(function(){
  var dfd = new $.Deferred();
  var add = $("#add");
  var remove = $("#remove");
  var content = $("#content");
  add.click(function(){
    var span = $("<span>我是点击按钮创建的元素</span>");
    $("span").length==0&&$("body").append(span);
    dfd.resolve();
  })
  remove.click(function(){
    var span = $("span");
    span&&span.remove();
  })
  dfd.done(function(){
    $("span").css("color","red");
  })
})
Copy after login

Now focus on the function. When we click the add button, we can see that the span element is added and the color turns red. Then we looked at the heterogeneous things in our code, the beginning var dfd = new $.Deferred(); and the dfd.resolve() in the add event function; and the last dfd.done(function(){ $("span").css("color","red");}).

 $.Deferred() is the focus of our introduction today---the delay object in JQ. The so-called delay means that it can run in a certain period of time in the future. Let’s look at a processing flow of the above code. In the above code, we call the dfd.done() method of the newly created delayed object and pass an anonymous function expression in the parameter position. In the processing of the click event When the function is executed, dfd.resolve() is called, and then the anonymous function we wrote in dfd.done() is executed. In this process, we can see that dfd puts the function in done in resolve position. dfd is a delay object, which obviously can change the execution order of functions.

When you look at the above code, if you think about it carefully, you will find that it is useful. We put the code that changes the color in a function, and call this function when clicked That's not great. It's so troublesome to write. In fact, the most common use of deferred objects is in AJAX. In the above code, after we click add, we click remove and then click add. At this time, we find that the word does not turn red this time. This is because the delayed object becomes invalid after the state changes. To put it bluntly, it is a one-time use.

Use of delayed objects

JQ implements the function of delayed objects for us. We generally call it Deferred or Promise, which is basically the same thing. To be precise, Promise is A subclass derived from Deferred.

When we use it, we first create a deferred object: var dfd = new $.Deferred().

The delayed object dfd has three states: pending, resolved, and rejected. We can check the state at this time by using the state method on the dfd object: dfd.state().

After dfd is created, its status is pending. After calling the resolve method: dfd.resolve(), its status will change to resolved and then the function in dfd.done() will be executed. dfd calls reject. After the method: dfd.reject(), its status will change to rejected and then the method in dfd.fail() will be executed, and the dfd object will not change after changing from pending to resolved or rejected. This That's why our code above can only make the text red after the first click.

Let’s take a look at the starting code. Our dfd.done() defines a function that turns the font red. After clicking on the function to execute, dfd calls resolve. After the status of dfd changes from pending to resolved, the method in done will be executed and the color will turn red.

Parameters can be passed between dfd.resolve() and dfd.done(). Now we make some modifications to the initial code:

//done里面的修改如下
dfd.done(function(color){$("span").css("color",color)})
//点击事件的处理函数修改如下
dfd.resolve("green");
Copy after login

We change the font color after clicking For green.

In addition, dfd has another function always: dfd.always(). The functions in always will be executed whenever the status of dfd changes from pending.

Each method of dfd will return a delay object, so there can be multiple done, fail, and always, which can be written directly as a chain call:

dfd.done (function(){}).done(function(){}).fail(function(){});

No matter which API of dfd, you can write multiple ones. At this time, we will You may consider whether its execution order can be guaranteed. We can rest assured that the order in which dfd's functions are executed is absolutely no problem and will be executed in the order we wrote it. Look at the following code:

dfd.done(function(){
  var span = $("<span>我是点击按钮创建的元素</span>");
  $("span").length==0&&$("body").append(span);
})
.done(function(color){
  $("span").css("color",color)});
})
Copy after login

The first function adds elements, and the second function changes and adds The color of the element.

  无论什么时候dfd三个API里面的函数都会在dfd的状态从pending变化之后才能执行,在异步的情况下如此,在同步的情况下也是。更确切的说dfd在调用dfd.resolve()之后已经执行过的done的里面的函数会立即执行,对于dfd.resolve()后面的done来说当程序走到它那时才会执行:

var dfd = new $.Deferred();
dfd.done(function(){console.log(1)});
dfd.done(function(){console.log(2)});
console.log("resolve before");
dfd.resolve();
console.log("resolve after");
dfd.done(function(){console.log(3)});
//resolve before,1,2,resolve after,3
Copy after login

延迟对象示例

  最开始我们使用JQ的AJAX的时候我们通常的写法是:

$.ajax({
 url:"x/y",
 type:"post",
 data:"{...}",
 contentType:"application/json; charset=utf-8",
 success:function(){},
 error:function(){}
})
Copy after login

  在1.5(好像是这个版本~)之后AJAX会返回一个Promise对象,继而我们可以写成下面这种:

$.ajax({
 url:"x/y",
 type:"post",
 data:"{...}",
 contentType:"application/json; charset=utf-8",
}).done(function(){})
.fail(function(){})
Copy after login

  看起来更骚气了一点,而且这我们还可以在加多个.done(function(){}),每个done处理不同的事情这样看起来比较清晰。

  已经知道延迟对象可以改变代码的执行顺序,假如我们又下面的代码:

$.ajax({
 url:"取数据",
 type:"post",
 contentType:"xxx"
}).done(function(data){
  $.ajax({
    url:"利用data取数据",
    data:data,
    type:"post",
    contentType:"xxxx"
  }).done(function(data){
    use data to _do sth...
  })
})
Copy after login

  我们会发现嵌套的有点多了,我们就可以利用延迟对象让他看起来更加好看一点:

var dfd = new $.Deferred();
$.ajax({
 url:"取数据",
 type:"post",
 contentType:"xxx"
}).done(function(data){
  dfd.resolve(data);
})
dfd.done(function(data){
  $.ajax({
    url:"利用data取数据",
    data:data,
    type:"post",
    contentType:"xxxx"
  }).done(function(data){
    use data to _do sth...
  })
})
Copy after login

  没有延迟对象我们一样能完成需要的功能,此时我们就需要一层一层嵌套我们处理过程了,而有了延迟对象我们就可以避免这种事了,他可以轻松控制代码的执行顺序,让代码看起来更请清晰。你可能会说我封装函数在合适的地方调不就行了,如果自己看自己写的代码没问题,但是换一个人他的滚动条可能就一直上上下下了。

  延迟对象的里一个作用就是可以合并AJAX的调用,比如一个接口取数据A另一个接口取数据B,AB都取到之后我们在利用这些数据做一些喜欢做的事,我们就可以利用延迟对象轻松实现。此时我们就可以利用JQ的$.when()来实现。$.when()就跟他的名字一样-当什么的时候-,他的参数可以是Promise对象,也可以是字符串(很少遇到不在介绍),他的返回结果也是一个Promise对象,下面看一个小例子: 

  var allData = {};
  var dataA = $.ajax({
    url:"获取A的URL",
    type:"post",
  }).done(function(data){
    allData.a = data;
  });
  var dataB = $.ajax({
    url:"获取B的URL",
    type:"post",
  }).done(function(data){
    allData.b = data;
  });
  $.when(dataA,dataB).done(function(){
    use allData to _do sth...
  });
Copy after login

  allData是保存所有数据的一个集合,dataA是第一个AJAX返回的Promise对象,dataB是第二个。$.when()的done方法执行的唯一条件就是dataA和dataB都执行成功。

  补充:dfd还有一对组合就是notify+progress当dfd对象的状态处于pending时可以调用dfd.nothfy(),调用之后dfd.progress()里面的函数会执行,只要dfd处于pending状态dfd.notify()就可以一直调用,同样也可以传递参数。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jQuery版本升级有哪些注意事项 

jQuery插件封装步骤详解

The above is the detailed content of jquery deferred object use case. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

How to use Xiaomi Auto app How to use Xiaomi Auto app Apr 01, 2024 pm 09:19 PM

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

How to use the little black box cdkey How to use the little black box cdkey Mar 12, 2024 pm 07:34 PM

How to use the Little Black Box cdkey? To put it simply, you can directly purchase games on the Steam platform from the Little Black Box, and you will receive a CDK redemption code after successful purchase. Next, use this redemption code in the Steam Mall to purchase the corresponding game. Many friends may not know how to use the small black box cdkey. Below I will explain the redemption steps in detail. I hope it will be helpful to you. How to use the Little Black Box cdkey 1. First copy the CDK redemption code obtained after purchasing the Little Black Box game. 2. Then start the Steam platform. 3. Click on the "Game" option in the menu in the upper left corner. 4. Find and click "Activate Product on Steam" in the new menu. 5. Click Next directly on the pop-up interface. 6. Purchase the small black box

See all articles