Home >Web Front-end >JS Tutorial >JavaScript asynchronous programming code writing specifications Promise study notes_javascript skills

JavaScript asynchronous programming code writing specifications Promise study notes_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:14:271072browse

My work has become a little easier recently, and I remembered a word promise that I always saw before, so I patiently studied it for a while.

1: What is Promise? Why is there this thing?

First of all, Promise was created to solve the problem of code writing in javascript asynchronous programming.
With the development of JavaScript, there are more and more asynchronous scenarios. The front-end has AJAX, setTimeout, etc., and the back-end Node is more asynchronous. According to the traditional approach, various callbacks are embedded in callbacks. Code can be confusing.
At this time, the CommonJS community proposed a specification called Promise/A, which defines how to write asynchronous code, including using when/then/resolve, etc. to organize asynchronous code.
Because this specification is very elegant, many people have implemented it, including Promise() natively supported by browsers, deferred in jQuery, when.js, etc.
Because these libraries all comply with this specification, it is enough to learn one. I mainly learned jQuery's deferred, so this article mainly talks about this implementation.

Two: jQuery’s deferred

First of all, regarding deferred objects, teacher Ruan Yifeng has written a very detailed article, the address is here. It is recommended that you read his article first and then continue reading.
As mentioned above, promises are used to solve asynchronous problems (such as ajax), so let's compare their differences.
The classic jQuery AJAX writing method is

Copy code The code is as follows:

$.ajax({
Type: "get",
url: "",
Success: function () {},
error; function () {}
});

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

And now jQuery’s AJAX writing method has become

Copy code The code is as follows:

$.ajax({
Type; "get",
URL: ""
}).done(function () {}).fail(function () {});

After success, the function in done will be called, and upon failure, the function in fail will be called.

When you see this, you may have questions. On which object are the done/fail methods located? What object does $.ajax() return and why are there these two methods?
The answer lies in the Deferred object introduced below.

jQuery provides a new type Deferred. Generated through $.Deferred(). For example

Copy code The code is as follows:

var def = $.Deferred();

This def inherits many methods, including done/fail/resolve/reject, etc.
So here we also know that the above $.ajax() actually returns this object.

Deferred objects have many methods. Here are some commonly used ones. For more information, please refer to API

The first thing is to naturally generate a def object. There are many methods here, such as:

Copy code The code is as follows:

var def = $.Deferred(); // Generate it yourself
$.ajax({}); // The ajax method also returns a def object
$.when(); // when method will also return a def object

Here, $.when() can be discussed separately. This method usually receives one or more deferred objects, and then determines the state of the object returned by $.when() based on the status of these deferred objects. One usage scenario is multiple ajax requests. If one of them fails, they will all be considered failures. Then you can pass in multiple ajax methods in $.when(), such as $.when($.ajax(), $. ajax()). Then $.when will return a def object (judged based on the results of these two requests).

Then after getting the def object, there are a series of methods to change the state of this object

Copy code The code is as follows:

def.resolve(); // Set the def object to completed, and then the function bound in def.done() will be executed immediately.
def.reject(); // Set the def object to have failed, and then the function bound in def.fail() will be executed immediately.
def.notify(); // When def object is executed, the corresponding callback is def.progress().

The next step is to set the callback method. The order corresponds to the above, that is, what callback will be called in what state

Copy code The code is as follows:

def.done(); // Corresponds to def.resolve();
def.fail(); // Corresponds to def.reject();
def.progress(); // Corresponds to def.notify();
// Special
def.always(); // Will be called on success or failure
def.then(); // Accept multiple functions, in order they are success (done), failure (fail) and progress (progress)

In fact, at this point, the usage of deferred objects is almost the same. However, jQuery also provides several APIs

Copy code The code is as follows:

// Check the current status class
def.isRejected();
def.isResolved();
def.state();

As the names of these APIs suggest, I won’t go into details. For details, you can check the jQuery API documentation given above.

There is another method, that is, sometimes we want to give an external def object, and then this object can set callbacks for various states, but cannot change its state, then we can use

Copy code The code is as follows:

def.promise();

Returns a promise object, which is a subset of the deferred object. You can use done/fail and other methods. There are no resolve/reject and other methods. It is mainly to protect the state of the def object from being modified by the outside.

At this point, I have finished talking about promises. You can now use it in your own projects. In addition, I wish you all a happy new year in advance and wish you all a prosperous Year of the Sheep^ ^.

Statement:
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