JavaScript Async code callbacks to Hell and the promise solution provided by jquery.deferred

Source: Internet
Author: User

Let's take a look at some of the problems that are often encountered in writing Ajax coding:

1. Because Ajax is asynchronous, all code that relies on Ajax to return results must be written in the Ajax callback function. This inevitably forms a nesting. The more asynchronous operations such as Ajax, the deeper the nesting level will be. The code will be less readable.

$.ajax ({    url:url,    data:dataobject,    success:function () {console.log ("I depend on Ajax result.");    error:function () {}}); Console.log ("I'll print before Ajax finished.");

2. Assuming that there is a dependency between AJAX requests, our code will form Pyramid of Doom (Pyramid Doom).

For example, we're going to finish this thing: There are 4 URL addresses for AJAX access, which requires an AJAX visit to 1th. After the 1th interview is complete. Use the returned data to access the 2nd, the 2nd interview after the 3rd ... With this to 4 all interviews completed.

In this way it seems to be the case:

$.ajax ({    url:url1,    success:function (data) {        $.ajax ({            url:url2,            data:data,            success: function (data) {                $.ajax ({                    //...});});}    );

3. Consider the scenario where if we send two AJAX requests at the same time and then do one of the next things after the two requests are successfully returned, think of the assumption that the callback will be appended to the respective invocation location just in the previous way. Isn't it very difficult?


The ability to see that asynchronous operations like Ajax in JavaScript can lead to complex levels of code nesting. Poor readability. Sometimes it is very difficult to even meet the needs. In order to solve such an asynchronous callback difficult problem, COMMONJS organization developed the Asynchronous Pattern programming specification promises/a. At the moment the specification has been implemented by a number of implementations, such as Q, When.js, jquery.deffered () and so on.

We learn the promise with jquery.deffered.


The state of Promise

The Promise object has 3 possible states: a positive State (resolved), a negative state (rejected), and a wait state (pending). The Promise object that was created at the beginning is in the pending state and can only be changed from pending to resolved or from pending to rejected state.

var df1 = $. Deferred (); Console.log (Df1.state ());//pendingvar DF2 = $. Deferred (); Df2.resolve ();//resolvedconsole.log (Df2.state ()); var df3 = $. Deferred (); Df3.reject (); Console.log (Df3.state ());//rejected
$. Deferred () Creates a deferred object (that is, the Promise object), and Deferred.state () is able to obtain the current state of the Promise object. Deferred.resolve () and Deferred.reject () are used to change the state of the Promise object.



Promise Adding a callback function

There are 3 states of the Promise object, and we are able to register the callback function for each of the 3 states.

When the promise is in a certain state, it triggers the callback function of the state's betting booklet.

var df = $. Deferred (); Df.done (function () {alert ("Success");}); Df.fail (function () {alert ("fail");}); Df.progress (function () {Alert ("Progress");}); Df.notify ();d f.resolve ();//Df.reject ();
Done (), fail (), progress () are registered in resolved, rejected, pending, respectively, in the state of the callback function. Resolve (), Reject (), notify () can trigger a pre-registration callback function.

Promise is supported for chained calls. The above code can be written in the following manner.

var df = $. Deferred (); Df.done (function () {alert ("Success");}). Fail (function () {alert ("fail");}). Progress (function () {Alert ("Progress");});


Promise supports multiple callback functions. are invoked in the order in which they are registered.

var df = $. Deferred (); Df.done (function () {alert ("First");}). Fail (function () {alert ("fail");}); Df.done (function () {alert ("Second");}); Df.done (function () {alert ("Third");}); Df.resolve ();


Deferred.always () Adds a callback function that will be called, regardless of whether promise is resolved or rejected state.

var df1 = $. Deferred (); Df1.always (function (type) {alert (type);}); Df1.resolve ("resolve"); var df2 = $. Deferred (); Df2.always (function (type) {alert (type);}); Df2.reject ("reject");

Progress () and notify () can be used to implement the progress bar effect. Because notify () agrees to call multiple times, reject () and resolve () can only be called once.

This is very well understood. As soon as the state becomes resolved or rejected. Can no longer change its state. There is no need.

var df = $. Deferred ();   Df.done (function () {alert ("Success");});  Df.fail (function () {alert ("fail");});  Df.progress (function () {Alert ("Progress");});    Resolve () Call 2 times, but can only trigger 1 times successdf.resolve ();  Df.resolve ();  var mudf = $. Deferred ();   Mudf.done (function () {alert ("Success");});  Mudf.fail (function () {alert ("fail");});  Mudf.progress (function () {Alert ("Progress");});    Each call to notify will trigger the progress callback function mudf.notify ("%10");  Mudf.notify ("%20");  

There is no difference between rejectwith (), Resolvewith (), Notifywith () functions and reject (), resolve (), notify (). The main difference is the run context in the callback function (this in the method) and the Parameter form.

Specific differences can refer to "Jquery.callbacks Series one: API use specific explanations" in this article Fire () and Firewith ().


The above simply describes how the promise is used. We can write Ajax code in a promise way. It is very easy to see that code nesting levels are low after using promise, and the code is growing vertically, not horizontally. and use promise. Ability to specify multiple AJAX callback functions.

Old Ajax notation $.ajax ({url: "test.html", Success:function () {alert ("Success");  }, Error:function () {alert ("error"); }});//Use Promise after $.ajax ("test.html"). Done (function () {}). Fail (function () {}). Do (function () {). Fail (function () {);

the deferred object in jquery differences from promise objects

Jquery. deferred related APIs. Some return the deferred object, and some return the Promise object. Most functions, such as done (), reject (), return the deferred object, and the $.when () and then () functions return the Promise object. Detailed documentation of the jquery API is available.

The official jquery explanation for Promise objects is:

This object provides a subset of the methods of the Deferred object (then, done, fail, always, progress, state and promise To prevent users from changing, the state of the Deferred.

Being able to see the Promise object is actually part of the deferred object, deferred object provides a way to change state, such as notify, reject, resolve, but the Promise object does not provide these methods.


The article started with the Ajax problem, 1 can be very easy to solve through promise. Issues 2 and 3 are addressed through $.when () and Deferred.then (). Because these 2 APIs are relatively complex, later articles analyze these 2 APIs.


References

" Asynchronous JavaScript and promise "author Acgtofe



JavaScript Async code callbacks to Hell and the promise solution provided by jquery.deferred

Related Article

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.