Promise makes people hate and love the existence, hate because the interview will be around it out of a lot of questions, and round and headache, love is really fragrant, who can not escape the true fragrant law.
1, concept,
A Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Promise is a constructor that has two characteristics:
- Promises have three states: pending, resolved, and Rejected. And the state is not affected by external factors.
- Once the state has changed, it cannot be modified. There can only be two processes: one is from pending to resolved, and the other is from pending to rejected. It is impossible to go from resolved to rejected. Once successful, it is impossible to fail again.
- Promises are executed as soon as they are created and cannot be canceled.
2, usage,
In general, promises are about solving asynchronous callback hell. What is callback hell?
A few images from the Internet give you a sense of the fear of being ruled by callback hell: the biggest drawback of callback hell is that the code is hard to read and write. Let’s look at the basic use of Promise:
new Promise((resolve, reject) = >{
. if(success) {
resolve(value);
}else {
reject(error); } }) Copy the code
Promise is a constructor that accepts a function argument. It accepts two arguments (resolve and Rejected), and the JS engine will deploy them automatically. The resolve function passes the value of the async function when it succeeds. It also changes the status from pending to resolved. The reject function passes the error message when the async fails. It also changes the state from pending to Rejected.
2.1, then ()
Once a Promise instance has been created, the then method on the prototype can be executed. The THEN method also takes two function arguments, the first as a result of the resolve callback and the second as a result of the Reject callback. The second argument is optional.
new Promise((resolve, reject) = > {
resolve(1);
}).then(
(value) = > console.log(value) / / 1
);
new Promise((resolve, reject) = > { reject("Something went wrong."); }).then( (error) = > console.log(error) // An error occurred ); Copy the code
Because the Promise object is created immediately, all actions that precede the resolve and reject functions are executed immediately:
new Promise((resolve, reject) = > {
console.log(2);
resolve(1);
}).then(
(value) = > console.log(value) 1 / / 2
); Copy the code
A Promise executes the THEN method and returns a new Promise object, so you can use chained calls.
new Promise((resolve) = > {
resolve(1);
})
.then((value) = > value + 1)
.then((value) = > console.log(value)); / / 2
Copy the code
The return value of the first THEN function can be passed as an argument to the second THEN function. What if the first then function still returns a Promise object? Is an asynchronous operation wrapped by a Promise:
new Promise((resolve) = > {
resolve(1);
})
.then(
(value) = >
new Promise((resolve) = > { resolve(3); }) ) .then((value) = > console.log(value)); / / 3 Copy the code
The argument passed by the second THEN function is the value passed in the resolved state of the Promise object returned by the first THEN function. The second then function executes only if the Promise returned by the first THEN succeeds.
2.2, the catch ()
In addition to the THEN function, there is a catch function on the Promise prototype that is only executed if the Promise is in the rejected state if there is an internal asynchron error.
new Promise((resolve, reject) = >{
throw new Error('test')
}).catch(err= >console.log(err)) // Error: test
Is equal to:new Promise((resolve, reject) = >{
throw new Error('test') }).then(null, err=>console.log(err)) // Error: test Copy the code
When the second argument and the catch function exist together, the catch function will not be executed:
new Promise((resolve, reject) = > {
throw new Error("test");
})
.then(null, (err) => console.log(err)) // Error: test
.catch((err) = > console.log(err));
Copy the code
Which Promise does the catch catch? The catch is the previous Promise error, that is, the Promise error returned by the then function:
new Promise((resolve, reject) = > {
throw new Error("test");
})
.then(null, (err) => {
throw new Error("test1");
}) .catch((err) = > console.log(err)); // Error: test1 Copy the code
Promise errors have a sort of bubbling mechanism; if there is no previous catch function to catch the error, it will eventually be caught by the catch.
new Promise((resolve, reject) = > {
throw new Error("test");
})
.then()
.catch((err) = > console.log(err)); // Error: test
Copy the code
As long as any Promise before the catch reports an error, it will eventually be caught by the catch. In general, it is not recommended to use the second argument of the THEN function to catch errors. The catch method described above can catch errors in the previous THEN method execution and is closer to synchronous (try/catch) writing. Therefore, it is recommended to always use the catch() method and not the second argument of the then() method. Then () returns a new Promise object, and catch() also returns a Promise object, again using chained calls:
new Promise((resolve, reject) = > {
throw new Error("test");
})
.then()
.catch((err) = > console.log(err)) // Error: test
.then((a)= > console.log(2)); / / 2 Copy the code
When a catch has caught an error, the following THEN method is executed. When no error is thrown, the catch is skipped and the following THEN method is executed. However, if a subsequent Promise has an error, the previous catch will not catch it.
new Promise((resolve, reject) = > {
throw new Error("test");
})
.then()
.catch((err) = > {
throw new Error("test1"); }) // Error: test .then((a)= > console.log(2)); Copy the code
A catch can be followed by a chain call to the THEN method, or a catch method, which receives an error thrown by the previous catch method.
2.3, the finally
In ES8, finally is a new method, which, unlike then and catch, does not track changes to the Promise object’s state, so it executes regardless of the Promise’s final state. And finally differs from THEN and catch in that it accepts no arguments.
new Promise((resolve) = > {
resolve(1);
})
.then((value) = > console.log(value)) / / 1
.finally((a)= > console.log(2)); / / 2
new Promise((a)= > { throw new Error("test"); }) .catch((err) = > console.log(err)) // Error test .finally((a)= > console.log(2)); / / 2 Copy the code
Finally returns a new Promise object, which is used the same way as then and catch. I won’t go into more detail here.
3. Other apis
In addition to the above methods on the Promise prototype, there are many other APIS for Promise.
3.1, Promise. All
As you can see from the literal sense, this method means’ all ‘, so it can accept multiple Promise objects. This method takes an argument that has an Iterator interface and each member is a Promise instance, and returns a new Promise object.
let p = Promise.all([
new Promise((resolve) = > {
resolve(1);
}),
new Promise((resolve) = > {
resolve(2); }), new Promise((resolve) = > { resolve(3); }), ]); Copy the code
In addition, the state of P can be resolved only when the state of all members in the accepted parameter is Resolved. If the state of one member is Rejected, then the state of P is rejected. When all the member states are resolved, the resolved state values of each member are spelled as an array and passed to the p callback function.
let p = Promise.all([
new Promise((resolve) = > {
resolve(1);
}),
new Promise((resolve) = > {
resolve(2); }), new Promise((resolve) = > { resolve(3); }), ]); p.then((result) = > console.log(result)); / / [1, 2, 3] Copy the code
When there is a member whose state is Rejected, the value of the first rejected state is returned to the catch method of P.
let p = Promise.all([
new Promise((resolve) = > {
resolve(1);
}),
new Promise((resolve, rejecct) = > {
rejecct(2); }), new Promise((resolve) = > { resolve(3); }), ]); p.catch((err) = > console.log(err)); Copy the code
Note that if a member is in the Rejected state and calls the catch method itself, it will not go through the CATCH method of the P object.
3.2, Promise. Race
Race returns the state of the Promise object and passes the value to the callback function of P, which takes the same arguments as promise.all.
let p = Promise.race([
new Promise((resolve) = > {
setTimeout((a)= > resolve(1), 100);
}),
new Promise((resolve) = > {
setTimeout((a)= > resolve(2), 50); }), new Promise((resolve) = > { setTimeout((a)= > resolve(3), 200); }), ]); p.then((result) = > console.log(result)); / / 2 let p = Promise.race([ new Promise((resolve) = > { setTimeout((a)= > resolve(1), 100); }), new Promise((resolve, reject) = > { setTimeout((a)= > reject(2), 50); }), new Promise((resolve) = > { setTimeout((a)= > resolve(3), 200); }), ]); p.catch((err) = > console.log(err)); / / 2 Copy the code
3.3, Promise. AllSettled
This method is new to ES2020. Like all, it returns a new Promise object and receives a set of Promise objects, but unlike all, when the execution ends, regardless of the state of each member’s Promise, The returned Promise object is finished.
let p = Promise.allSettled([
new Promise((resolve) = > {
resolve(1);
}),
new Promise((resolve, rejecct) = > {
rejecct(2); }), new Promise((resolve) = > { resolve(3); }), ]); p.then((value) = > console.log(JSON.stringify(value))); // [{status:"fulfilled",value:1},{status:"rejected",reason:2},{status:"fulfilled",value:3}] Copy the code
Sometimes the asynchronous request does not care whether it succeeds or not. This method fits the scenario well and returns an array with two states for each object, fulfilled and rejected, which can be filtered to see the error information.
3.4, Promise. Resolve
Convert an object to a Promise object.
Promise.resolve("foo");
Equivalent to;new Promise((resolve) = > resolve("foo"));
Copy the code
If the promise. resolve argument is a Promise instance, return the instance intact:
let p = new Promsie((resolve) = > resolve(1));
let p1 = Promise.resolve(p);
p === p1; // true
Copy the code
When the argument is a Thenable object, that is, an object with a THEN method, a Promise object is returned and the THEN method is executed immediately.
let thenable = {
then: function (resolve, reject) {
resolve(1);
},
};
let p = Promise.resolve(thenable); p.then((value) = > console.log(value)); / / 1 Copy the code
When the parameter is not a Thenable object, because the parameter is not asynchronous, after promise. resolve, the state is resolved, and then the original value is output.
1.The parameter is a normal objectlet obj = {
name: '1'
}
let p = Promise.resolve(obj);
p.then(value= >console.log(value)) // {name: '1'} 2.Parameter is a basic data typelet num = '1'; let p = Promise.resolve(num); p.then(value= >console.log(value)) / / 1 Copy the code
When no argument is passed, a Promise object with the resolved state is returned.
3.5, Promise. Reject
Return a Promise object with the status rejected and the parameters passed as error messages to subsequent methods.
let num = "1";
let p = Promise.reject(num);
p.then(null, (err) => console.log(err)); / / 1
Copy the code
When the argument is a thenable object, instead of an error message, the thenable object is returned.
let thenable = {
then: function (resolve, reject) {
reject(1);
},
};
let p = Promise.reject(thenable); p.then(null, (err) => console.log(err === thenable)); // true Copy the code
After the language
Related articles:
- Take you relearn ES6 | var, let and the difference between const
- Take you relearn ES6 | Promsie
- Take you relearn ES6 | Generator
- Take you relearn ES6 | Async and Await
- Take you relearn ES6 | Set and Map
- Take you relearn ES6 | Symbol (more than just a new data type)
- Take you relearn ES6 | Exprort (keep in mind that the output is variable)
- Take you relearn ES6 | proxy and defineProperty
I think it’s ok, please give me a thumbs up when I leave, and we can study and discuss together!
You can also follow my blog and hope to give me a Start on Github, you will find a problem, almost all my user names are related to tomatoes, because I really like tomatoes ❤️!!
The guy who wants to follow the car without getting lost also hopes to follow the public account or scan the qr code below 👇👇👇.
I am a primary school student in the field of programming, your encouragement is the motivation for me to keep moving forward, 😄 hope to refueling together.
This article was typeset using MDNICE