What is promise?
Promise is a solution to asynchronous programming that is more reasonable and powerful than traditional callback functions and events.
A Promise is simply a container that holds something (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations.
Features:
The status of an object is not affected. The Promise object represents an asynchronous operation with three states: Pending, fulfilled and Rejected. Only the result of an asynchronous operation can determine which state is currently in, and no other operation can change that state. That’s where the name Promise came from. Once the state changes, it never changes again, and you can get this result at any time. There are only two possibilities for the state of the Promise object to change: * From pending to depressing and from pending to Rejected. As soon as those two things happen, the state freezes, it can’t change anymore. Adding a callback function to the Promise object will get this result immediately. With the Promise object, you can express asynchronous operations as a flow of synchronous operations. Disadvantages:
First, there’s no way to cancel a Promise. Once a Promise is created, it executes it immediately. Second, if the callback function is not set, errors that run inside a Promise cannot be reflected externally. When pending, there is no way to know where the progress is.
The basic usage, ES6, states that a Promise object is a constructor that generates a Promise instance.
The following code creates an instance of Promise.
The resolve function changes the state of the Promise object from “incomplete” to “successful.” (From Pending to Resolved). Called when the asynchronous operation succeeds, passing the result of the asynchronous operation as a parameter;
The Reject function changes the state of the Promise object from “unfinished” to “failed”. Called when an asynchronous operation fails and passes an error reported by the asynchronous operation as a parameter.
Once the Promise instance is generated, you can use the then method to specify the resolve and Rejected state callback functions, respectively.
The first callback is called when the Promise object’s state becomes Resolved,
The second callback is called when the state of the Promise object changes to Rejected.
The second function is optional and does not need to be provided.
Both of these functions accept as arguments a value passed from the Promise object.
When the state of the Promise instance changes to Resolved after the specified time, the callback function bound to the then method is triggered.
Promises are implemented as soon as they are created.
- Promise.prototype.then()
The Promise instance has then methods, which are defined on the prototype object.
It adds a callback function to the Promise instance when the state changes.
As mentioned earlier, the first argument to the THEN method is the callback in the Resolved state and the second argument is the (optional) callback in the Rejected state.
The then method returns a new Promise instance (note, not the original Promise instance) and can therefore be chained, where the then method is followed by another then method.
The chained THEN allows you to specify a set of callback functions that are called in order. In this case, the previous callback may return a Promise object (that is, an asynchronous operation), and a callback will wait for the state of the Promise object to change before it is called.
- Promise.prototype.catch()
The promise.prototype. catch method is an alias for. Then (null, Rejection) that specifies the callback when an error occurs.
Errors on Promise objects bubble backwards until they are caught, meaning they are always caught by the next catch statement.
- Promise.prototype.finally()
The finally method is used to specify actions that will be performed regardless of the final state of the Promise object.
4. Pomise. The use of all
The promise.all (iterable) method returns an instance of a Promise that is resolved when all promises in iterable arguments are “resolved” or when the arguments do not contain the Promise; If a promise fails (Rejected), the instance calls back (reject) because of the result of the first failed promise. Promse.all is useful when processing multiple asynchronous processes, such as displaying only the Loading icon before displaying two or more Ajax data on a page. In particular, the order of the data in the array of the successful results obtained by Promise.all is the same as that received by Promise.all, that is, the result of P1 is first, even though the result of P1 is obtained later than p2. This has one great benefit: When developing request data on the front end, there are occasional scenarios where multiple requests are sent and the data is retrieved and consumed according to the order in which they are requested, using Promise.all is a surefire way to solve this problem.
The promise.race (iterable) method returns a Promise. Once a Promise in the iterator is resolved or rejected, the returned Promise is resolved or rejected. Promse.race, as the name suggests, means a race, which means that a Promise. Race ([P1, P2, P3]) returns the fastest result, regardless of whether the result itself is a success or a failure. The principle is quite simple, but in practical application has not thought of what use scenarios will be used. Example: Timeout cancellation Let’s look at how to implement a timeout mechanism using promise.race. Of course XHR has a timeout attribute, which can also be used to simply timeout, but in order to support multiple XHR timeouts and other functions at the same time, we used an easy-to-understand asynchronous way to cancel ongoing operations by timeout in XHR.
- Let’s first look at how to implement timeouts in promises. A timeout is an operation that takes place after a certain amount of time has elapsed. Let’s start with a simple function that calls setTimeout in a Promise.
The concept of promise objects is very important to keep in mind here. We can implement a simple timeout mechanism by putting the delayPromise we just mentioned in the promise. race along with other Promise objects.
To distinguish the Error object type, we’ll subclass TimeoutError.
An Error object is a build in object built into ECMAScript.
We can’t perfectly create a class that inherits from Error due to stack trace and so on, but our goal here is just to differentiate ourselves from Error, and we’ll create a TimeoutError class to do that.
In ECMAScript6, you can use the class syntax to define inheritance relationships between classes.
It is used in the same way as a normal Error object, using a throw statement, as shown below.
❤️ Read three things
If you feel this piece of content is quite enlightening for you, I’d like to invite you to help me three little busy: point a “yes”, let more people can see this piece of content (like don’t agree with, is all play rascal -_ -) point attention don’t get lost ~ let’s focus on long-term relationship (senior front-end architecture to help), my column face questions before send you senior
Article reprinted to: front-end advanced walkthrough
Author: Front-end advancer