Javascript asynchronous programming code writing specification Promise learning notes, promise learning notes

Source: Internet
Author: User

Javascript asynchronous programming code writing specification Promise learning notes, promise learning notes

Recently, my work was easy. I remembered the word promise which I used to see before. So I learned it with patience.

I. What is Promise? Why is there this?

First of all, Promise is designed to solve the problem of code writing in javascript asynchronous programming.
With the development of javascript, there are more and more asynchronous scenarios. The frontend includes AJAX and setTimeout, And the backend Node is more asynchronous. According to the traditional practice, there are various types of callback embedded callbacks. Code can confuse people.
At this time, the CommonJS community proposed A specification called Promise/A +, which defines how to write asynchronous code, including using when/then/resolve to organize asynchronous code.
Due to its elegance, many people have successively implemented this specification, including Promise () supported by the browser native, deferred in jQuery, and when. js.
Because these databases comply with this specification, you can learn one. I mainly learned about jQuery's deferred, so this article focuses on this implementation.
 
Ii. deferred of jQuery

First of all, regarding the deferred object, instructor Ruan Yifeng wrote a very detailed article. Here is the address. We recommend that you first read his article and continue reading it.
As mentioned above, promise is used to solve asynchronous (such as ajax), so let's compare their differences.
The typical jQuery AJAX method is

Copy codeThe Code is as follows:
$. Ajax ({
Type: "get ",
Url :"",
Success: function (){},
Error; function (){}
});

The success and error parameters are the callback functions for success/failure.

Now jQuery AJAX is written

Copy codeThe Code is as follows:
$. Ajax ({
Type; "get ",
Url :""
}). Done (function () {}). fail (function (){});

After the operation is successful, the function in done is called. If the operation fails, the function in fail is called.

You may have questions about the object on which the done/fail Methods belong? $. What objects is returned by ajax ()? Why are there two methods?
The answer is the Deferred object described below.

JQuery provides a new type of Deferred. Generated by $. Deferred. For example

Copy codeThe Code is as follows:
Var def = $. Deferred ();

This def inherits many methods, such as done/fail/resolve/reject.
So here we know that the above $. ajax () actually returns this object.
 
There are many methods for deferred objects. Here we will introduce several common methods. For more information, see API
 
First, a def object is generated. There are many methods, such:

Copy codeThe Code is as follows:
Var def = $. Deferred (); // generated by yourself
$. Ajax ({}); // The def object returned by the ajax method is also
$. When (); // The when method also returns a def object

Here, $. when () can be discussed separately. This method usually receives one or more deferred objects, and then decides $ based on the status of these deferred objects. the status of the object returned by when. One application scenario is multiple ajax requests. If one of them fails, it can be found at $. multiple ajax methods are input in when (), for example, $. when ($. ajax (), $. ajax ()). Then $. when returns a def object (determined based on the two request results ).
 
Then we get the def object, and we have a series of methods to change the object state.

Copy codeThe Code is as follows:
Def. resolve (); // set the def object to completed, and then immediately execute the function bound to def. done.
Def. reject (); // set the def object to a failed one, and then immediately execute the function bound to def. fail.
Def. Y (); // when the def object is being executed, the corresponding callback is def. progress ().

The next step is to set the callback method. The order corresponds to the above, that is, the status of the callback that will be called.

Copy codeThe Code is as follows:
Def. done (); // corresponding to def. resolve ();
Def. fail (); // corresponding to def. reject ();
Def. progress (); // corresponding to def. Y ();
// Special
Def. always (); // call if the call succeeds or fails.
Def. then (); // accepts multiple functions. In sequence, they are successful (done), fail (fail), and progress (progress)

In fact, the usage of the deferred object is almost the same here. However, jQuery also provides several APIs

Copy codeThe Code is as follows:
// Check the current status
Def. isRejected ();
Def. isResolved ();
Def. state ();

As the name suggests, these APIs are not specific. For details, refer to the jQuery api document above.
 
There is another way, that is, sometimes we want to give an external def object, and then this object can be set with callbacks of various states, but it cannot change its state, then we can use

Copy codeThe Code is as follows:
Def. promise ();

Return a promiese object, which is a subset of the deferred object. You can use methods such as done/fail without resolve/reject, to protect the external users from modifying the state of the def object.

Now, all about promise has been finished. Now you can use it in your own project. In addition, we will give you an early-Year greeting and wish you a happy New Year. ^.

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.