Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Today is the second day of The 11th, let’s review the use of Promise.
What is the Promise
In JavaScript, a promise is an object that returns a desired result in the future, not now.
Because values are returned by promises in the future, promises are well suited for handling asynchronous operations.
For example
Let’s say I decide I’m going to relearn JavaScript next month, but I don’t actually know if I have the time or energy to do it next month. I may or may not do it.
A promise has three states:
- Pending: An initial state that has neither completed nor failed.
- This is a big pity
- A: Rejected/rejected
A promise starts with a pending state and eventually goes towards a fulfilled promise or rejected failure.
Create a Promise
To create a Promise object, we use the Promise constructor
let completed = true;
let learnJS = new Promise((resolve, reject) = > {
if (completed) {
resolve("I have completed my JS study");
} else {
reject("I haven't finished my JS study."); }});Copy the code
The Promise constructor takes a function as an executor that takes two arguments, resolve and reject, representing success and failure.
When we new Promise(), the executor function executes by default.
Let’s print it out
console.log(learnJS);
// This is a big pity. {< depressing >: 'I have finished learning '}
Copy the code
As you can see, the Promise has become a pity state. Because completed is true, the Promise executor function call will call resolve and reject if it fails.
To see pending status, we use setTimeout to delay the return of the result
let completed = true;
let learnJS = new Promise((resolve, reject) = > {
setTimeout(() = > {
if (completed) {
resolve("I have completed my JS study");
} else {
reject("I haven't finished my JS study."); }},5 * 1000);
});
console.log(learnJS);
// Output: Promise {
}
Copy the code
Now you can see that the promise is in a pending state.
Wait five seconds before printing
console.log(learnJS);
// This is a big pity. {< depressing >: 'I have finished learning '}
Copy the code
The promise has become a pity state, because 5 seconds later setTimeout executes the resolve function.
When we change completed to false
let completed = false;
let learnJS = new Promise((resolve, reject) = > {
if (completed) {
resolve("I have completed my JS study");
} else {
reject("I haven't finished my JS study."); }});console.log(learnJS);
// output: {
: 'I don't finish JS learning '}
// Uncaught (in promise
Copy the code
The promise becomes rejected, and the console gets an error because the reject function is called.
Once the promise state becomes a pity or rejected state, it cannot be changed. When we new a Promise object, it stays in a pending state until a call to resolve/ Reject produces a result.
To do something with a promise’s resolve/ Reject state, we can call the promise’s then(), catch(), and finally() callback functions.
Then, catch, finally
1) then ()
Then () is used to set the callback when the Promise becomes the Resolved state.
The then() method can pass in two callback functions. The second, onRejected, can be used to set the callback if Rejected fails.
promiseObject.then(onFulfilled, onRejected);
Copy the code
Let’s write a function that returns a Promise object
function makePromise(completed) {
return new Promise((resolve, reject) = > {
setTimeout(() = > {
if (completed) {
resolve("I have completed my JS study");
} else {
reject("I haven't finished my JS study."); }},5 * 1000);;
});
}
Copy the code
Change learnJS to return functions, and then to set the appropriate callback function
let learnJS = makePromise(true);
learnJS.then(
success= > console.log(success),
fail= > console.log(fail)
);
// output after 5 seconds: I have finished learning JS
Copy the code
2) the catch ()
Catch () sets the promise to become the callback if Rejected fails.
let learnJS = makePromise(false);
learnJS.catch(
fail= > console.log(fail)
);
// output after 5 seconds: I am not finished learning JS
Copy the code
3) finally ()
Finally () is used to set whether promise becomes Resolved/Rejected succeeds or fails.
Take the following example
function createApp() {
// ...
}
learnJS
.then(
(success) = > {
console.log(success);
createApp();
}
).catch(
(fail) = > {
console.log(fail); createApp(); });Copy the code
The createApp function is called whenever the promise state succeeds or fails, so we’ll use finally() below
learnJS
.then(success= > console.log(success))
.catch(fail= > console.log(fail))
.finally(() = > createApp());
Copy the code
In this way, the code logic is clearer and easier to maintain.
conclusion
- Promise is used to return a value at some future time.
- Promise starts with a pending state and ends with a fulfilled or rejected state.
- Use then()/catch() functions to set successful or failed callbacks.
- Use finally() to set up the callback function that executes regardless of success or failure.
Welcome to pay attention to my public number [xiaoshuai’s programming notes], follow me a little bit of progress every day