JavaScript asynchronous Programming code Writing Specification Promise learning notes _javascript skills

Source: Internet
Author: User
Tags what callback

Recently work relaxed point, think of the previous always see a word promise, so patience to learn a bit.

One: What is promise? Why would there be such a thing?

First, the promise is created to address the way JavaScript writes code in asynchronous programming.
With the development of JavaScript, there are more and more asynchronous scenes. The front end has ajax,settimeout, and the backend node is more asynchronous. In traditional practice, it is the various callback nesting callbacks. Code can turn people around.
This time, the COMMONJS community presented a specification called promise/a+, which defines how to write asynchronous code, including the use of When/then/resolve to organize asynchronous code.
This specification is very elegant, so many people have implemented this specification, including the Promise () of the native support of the browser, the Deferred,when.js in jquery, and so on.
Since these libraries all conform to the specification, it is OK to learn one. I mainly studied the deferred of jquery, so this article mainly talk about this implementation.

Two: The deferred of jquery

First of all, on the deferred object, Nanyi teacher has an article written in very detailed, address point this. Suggest you can look at his article first, and then continue to look down.
As mentioned above, promise is to solve asynchronous (such as Ajax), then we compare their differences.
The classic jquery ajax notation is

Copy Code code as follows:

$.ajax ({
Type: "Get",
URL: "",
Success:function () {},
Error function () {}
});

Where the success and error parameters are the callback functions at the time of success/failure.

And now jquery's Ajax has been written as

Copy Code code as follows:

$.ajax ({
Type "Get",
URL: ""
). Done (function () {}). Fail (function () {});

The success of which will call the done inside function, failure will call fail inside the function.

You may have questions to see here, Done/fail. Which objects are these methods? $.ajax () What object is returned, why are these two methods?
The answer is the deferred object described below.

jquery provides a new type of deferred. Through $. Deferred () to generate. For example

Copy Code code as follows:

var def = $. Deferred ();

This def inherits a lot of methods, such as Done/fail/resolve/reject.
So here we also know, the above $.ajax () actually return is this object.

There are a number of ways to deferred objects, here are some common, more can reference API

The first thing is naturally to generate a Def object. There are many ways to do this, such as:

Copy Code code as follows:

var def = $.    Deferred (); Build Your Own
$.ajax ({}); The Ajax method returns a Def object as well
$.when (); When method also returns a Def object

Here, $.when () alone, this method usually receives one or more deferred objects, and then determines the state of the object returned by $.when () based on the state of those deferred objects. One use scenario is multiple AJAX requests, and if one of these failures fails, then multiple Ajax methods, such as $.when ($.ajax (), $.ajax ()) can be passed in $.when (). $.when then returns a Def object (based on the results of these two requests).

Then we get the Def object, and we have a series of ways to change the state of the object.

Copy Code code as follows:

Def.resolve (); The Def object is set to complete, and the function that is bound to the Def.done () is executed immediately.
Def.reject (); The Def object is set to fail, and the function that is bound to the Def.fail () is executed immediately.
Def.notify (); Def object execution, the corresponding callback is def.progress ().

Then there is the method of setting the callback, the order and the above, and what state will invoke to what callback

Copy Code code as follows:

Def.done (); corresponding def.resolve ();
Def.fail (); corresponding Def.reject ();
Def.progress (); corresponding def.notify ();
Of special
Def.always (); Success or failure will call
Def.then (); Accept multiple functions, sequentially succeeding (done), failure (fail), and ongoing (progress)

In fact, the use of deferred objects is almost the same here. But jquery also provides a few APIs

Copy Code code as follows:

Check the current status class
Def.isrejected ();
Def.isresolved ();
Def.state ();

These APIs, as the name suggests, do not specifically, you can view the above jquery API documentation.

There is also a way that sometimes we want to give an external Def object, and then the object can set a callback for various states, but not change its state, then you can use

Copy Code code as follows:

Def.promise ();

Returns a Promiese object, is the deferred object's subset, may use Done/fail and so on method, does not have the resolve/reject and so on method, mainly is protects does not allow the external to modify the Def object the state.

At this point, about promise has been all finished, we can now use it in their own projects, and early for everyone to worship an early years, I wish you a happy goat's Day ^ ^.

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.