Frontend programming improvement journey (9) ---- delay object, journey ----

Source: Internet
Author: User
Tags openid

Frontend programming improvement journey (9) ---- delay object, journey ----

Recently, we have made an internal recommendation project. When we enter the project homepage, we need to determine the pre-called interface. According to past habits, we should put the code executed after the called interface into the ajax request success for execution. This is certainly acceptable, but the code organization and readability are not that high. You can view the api on the Jquery official website to find the concept of deferred object (latency object.

1. API document translation:

Delayed object, introduced in jquery1.5, is a chain function object generated by calling the jQuery. Deferred () method. It can register multiple callbacks to the callback queue, extract the callback queue, and pass the success or failure status of any asynchronous or synchronous functions.
The delayed object is chained, similar to the jquery object chain, but it has its own method. After the creation, you can use any of the methods involved below, whether it is a direct chained call, or save the object to a variable, and call one or more methods on the variable.

  • Deferred. always ()
The add operation method is called no matter whether the delayed object is in the resolved or rejected status.
  • Deferred. done ()
Add operation method, called only when the delayed object is in the resolved status
  • Deferred. fail ()
Add operation method. A delayed object is called only when it is rejected.
  • Deferred. isRejected ()
Determines whether a delayed object is rejected.
  • Deferred. isResolved ()
Determines whether a delayed object is in the resolved state.
  • Deferred. Policy ()
Call the ongoing callback on the delayed object of a given variable.
  • Deferred. policywith ()
Call the ongoing callback on the delayed object of a given variable and context.
  • Deferred. pipe ()
Utility method used to filter and or chain latency
  • Deferred. progress ()
The add operation is called when the notification is passed when the delayed object is generated.
  • Deferred. promise ()
Returns the delayed promise object.
  • Deferred. reject ()
Reject a delay object and call any given parameter failure callback.
  • Deferred. rejectWith ()
Reject the callback object and call the failed callback for any given context and parameters.
  • Deferred. resolve ()
Resolves a delay object and calls the complete callback of any given parameter.
  • Deferred. resolveWith ()
Resolves a delay object and calls the complete callback of any given context and parameters.
  • Deferred. state ()
Determines the status of the current delayed object.
  • Deferred. then ()
When the delayed object is resolved, rejected, or added in progress, it is called.
  • JQuery. Deferred ()
Constructor of the delayed object.
  • JQuery. when ()
Provides a method to execute a callback function based on one or more objects. The callback function is often a delayed object representing asynchronous events.
  • . Promise ()
A promise object is returned when all the actions bound to the set, queue, or none are completed.

Ii. Analysis and use of delayed objects:

It is not difficult to draw a conclusion that the above APIs include the construction of the delayed object, the method for setting the delay state, and the method for monitoring the delay state.


Data Structure of the delayed object

Delayed objects include three states: resolved (resolved), rejected (unresolved), and SS (in progress ). The three statuses can be viewed in real time using the delayed object state method.


View delayed object status

The delayed object is the callback function solution of jquery. latency, as the name suggests, means that the object will be executed at a certain point in the future. Similar to the delay method in jquery animation functions, the difference is that the latter has a fixed delay time, the delayed object is the time to judge the delayed execution through the fixed state.

Var dtd = $. Deferred (); // create a new deferred object var wait = function (dtd) {var tasks = function () {alert ("execution completed! "); Dtd. resolve (); // change the execution status of the deferred object}; setTimeout (tasks, 5000); return dtd ;};$. when (wait (dtd )). done (function () {alert ("Haha, success! ") ;}). Fail (function () {alert (" error! ");});

  The above code execution flowchart:



In the preceding code example, a delayed object is defined as a global object, which causes a delay and can be changed at any time.

Method 1:

Var dtd = $. Deferred (); // create a new Deferred object var wait = function (dtd) {var tasks = function () {alert ("execution completed! "); Dtd. resolve (); // change the execution status of the Deferred object}; setTimeout (tasks, 5000); return dtd. promise (); // return the promise object. The promise object is only open to Methods unrelated to the state, that is, the three state methods are not open and cannot be set}; var d = wait (dtd ); // create a new d object and operate on the object $. when (d ). done (function () {alert ("Haha, success! ") ;}). Fail (function () {alert (" error! ") ;}); D. resolve (); // at this time, this statement is invalid

The preceding Code indicates that the return value of the wait function is a promise object. It is not difficult to find out by the data structure of the promise object that has all the methods to delay the object except the State modification method, that is, the promise object cannot change the execution status, which prevents external changes to the status. Data Structure of the promise object


Method 2:

Build the delayed object into a local variable inside the function to better implement encapsulation and prevent external changes to the State.

Var wait = function (dtd) {var dtd = $. Deferred (); // inside the function, create a new Deferred object var tasks = function () {alert ("execution completed! "); Dtd. resolve (); // change the execution status of the Deferred object}; setTimeout (tasks, 5000); return dtd. promise (); // returns the promise object}; $. when (wait ()). done (function () {alert ("Haha, success! ") ;}). Fail (function () {alert (" error! ");});

Method 3:

The function name is passed in as the $. Deferred () parameter. The latency object generated by $. Deferred () is passed in as the wait function parameter.

Var wait = function (dtd) {var tasks = function () {alert ("execution completed! "); Dtd. resolve (); // change the execution status of the Deferred object}; setTimeout (tasks, 5000); return dtd. promise (); // returns the promise object}; $. deferred (wait ). done (function () {alert ("Haha, success! ") ;}). Fail (function () {alert (" error! ");});

$. Deferred () method execution status


Iii. Project usage:

Ledi uses the second method in the internal push project, which defines the delayed object as a local variable and returns the promise object. In this example, the promise object and the delayed object cannot change the state, and the record and listening method of the delayed State are the same.

Function loadInternalHost () {var dtd = $. deferred (); dtd. resolve (); return dtd. promise (); // return another deferred object on the original defferred object. Both objects record the state of the original deferred object, but the latter cannot change the State. Other methods are the same}



Promise records the delay status

When two interfaces are called separately, the latency listening function allows you to specify a callback for multiple events.

Run the following code to obtain the data of the cities and announcements, and then load the data.

$. When (getInternalRecommendCitys (), getComment ()). done (function () {getInternalRecommendJobAdList (oldSearchData. keyWord, oldSearchData. locId) ;}); function getInternalRecommendCitys () {var dtd =$. deferred (); $. ajax ({type: "get", data: {"openId": openId}, dataType: "json", url :".. /api/InternalInfo/InternalRecommendCitys ", success: function (data) {$ city = $ (" # citySelect "); for (var I = 1; I <data. length; I ++) {$ str = $ ("<option> </option>"); $ str. text (data [I]. name); $ str. val (data [I]. value); $ city. append ($ str); dtd. resolve ();} // import the available cities to the selection list}, error: function () {dtd. resolve () ;}}); return dtd. promise ();} function getComment () {var dtd = $. deferred (); $. ajax ({type: "get", data: {"openId": openId}, dataType: "json", url :".. /api/InternalInfo/GetComment ", success: function (data) {$ (". notice-content pre "pai.html (data. data); dtd. resolve () ;}, error: function () {dtd. resolve () ;}}); // obtain the announcement data return dtd. promise ();}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.