My work has been a little easier recently. I remembered a word promise I always saw before, so I went down to study it patiently.
1: What is a Promise? Why is this thing there?
First of all, Promise is created to solve the problem of code writing during asynchronous programming of javascript.
With the development of JavaScript, there are more and more asynchronous scenarios. The front end has AJAX, setTimeout, etc., and the backend Node is asynchronous. According to traditional practice, it is to embed callbacks in various callbacks. Code can make people dizzy.
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 this specification one after another, including the browser native support Promise(), deferred in jQuery, when.js, etc.
Because these libraries meet this specification, just learn one. I mainly learned deferred of jQuery, so this article mainly talks about this implementation.
Two: jQuery's deferred
First of all, about the deferred object, Mr. Ruan Yifeng wrote an article in detail, please click here. It is recommended that you read his article first and then continue reading.
As mentioned above, promises are designed to solve asynchronous (such as ajax), so let’s compare their differences.
The classic jQuery AJAX is written as
The code copy is as follows:
$.ajax({
type: "get",
url: "",
success: function () {},
error; function () {}
});
The success and error parameters are callback functions when success/failure.
Now jQuery's AJAX writing method has become
The code copy is as follows:
$.ajax({
type; "get",
url: ""
}).done(function () {}).fail(function () {});
After success, the function in done will be called, and if the function in fail is called, the function in fail will be called.
After seeing this, you may have questions, which object are these methods done/fail? What object does $.ajax() return and why are there these two methods?
The answer is in the Deferred object introduced below.
jQuery provides a new type of Deferred. Generate with $.Deferred(). For example
The code copy is as follows:
var def = $.Deferred();
This def inherits many methods, including done/fail/resolve/reject, etc.
So here we know that the above $.ajax() actually returns this object.
There are many methods for deferred objects. Here are several commonly used ones. For more information, please refer to the API.
The first thing is to naturally generate a def object. There are many ways here, such as:
The code copy is as follows:
var def = $.Deferred(); // Generate it yourself
$.ajax({}); // The ajax method returns also a def object
$.when(); // when method will also return a def object
Here, $.when() can be talked about 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 of the usage scenarios is multiple ajax requests. If one of them fails, it is considered a failure. Then you can pass multiple ajax methods into $.when(), such as $.when($.ajax(), $.ajax()). Then $.when will return a def object (judged based on the results of these two requests).
Then you get the def object, and there are a series of methods to change the state of this object.
The code copy is as follows:
def.resolve(); // Set the def object to be completed, and then the function bound to def.done() will be executed immediately.
def.reject(); // Set the def object to have failed, and then the function bound to def.fail() will be executed immediately.
def.notify(); // During the execution of the def object, the corresponding callback is def.progress().
Next is the method of setting the callback, the order corresponds to the above, that is, what state will call to what callback
The code copy is as follows:
def.done(); // Corresponding to def.resolve();
def.fail(); // Corresponding to def.reject();
def.progress(); // Corresponding to def.notify();
// Special
def.always(); // Called if successful or failed
def.then(); // Accept multiple functions, in order, success, failure, and progress
In fact, at this point, the usage of the deferred object is almost the same. However, jQuery also provides several APIs
The code copy is as follows:
// Check the current status class
def.isRejected();
def.isResolved();
def.state();
As the name suggests, these APIs will not be discussed in detail. For details, you can check the jQuery API documentation given above.
There is another method, which is that sometimes we want to give an external def object, and then this object can set callbacks for various states, but cannot change its state, so we can use it.
The code copy is as follows:
def.promise();
Return a promisee object, which is a subset of the deferred object. You can use done/fail and other methods, without resolve/reject and other methods. It is mainly to protect the state of the def object from being modified from the outside.
At this point, all the promises have been discussed. You can now use them in your projects. In addition, I wish you a happy early years in advance. I wish you all a happy Year of the Sheep^^.