Writing in the front
A month ago promised to sort out the understanding of the promise and handwritten promise code, until now have not had time to cash, it is time to cash their promise. In this paper, the relevant knowledge points of promise are sorted out and summarized based on the video of STATION B and my own understanding. If necessary, you can refer to them by yourself through the portal. The follow-up will continue to cash their promise, find time to sort out the handwritten promise code article.
Promise tutorial (Video) : Jag Classroom -2020 Best Understood Promise tutorial
Understanding the Promise method (video) : Promise method
Why do WE need Promise
Suppose you have a requirement scenario where you first need to get an ID by making a request, then get a user name through the id request interface, and then get the user’s mailbox by making a request based on the user name. If you make a request using Ajax, you need to make a second request in the success callback of the first request, and a third request in the success callback of the second request. If additional data needs to be requested, this nesting creates a callback hell that promise was born to solve to make our code more elegant.
Basic use of promise
- Promise is a constructor that passes
new
The keyword instantiates the object.
1. New Promise((resolve, reject) => {})
2. Accept a function as an argument
3. Accept resolve and reject in the argument function
- A Promise instance has two properties:
1
2. The result: the results
The state of the Promise (to distinguish which function is executed in the then method)
The state of the promise
The first state: Pending
This is a big pity. The second state is very depressing.
My last state is rejected(rejected).
Promise state changes
If resolve and Reject are not called, the state of the returned Promise instance is pending, but the state of the current Promise object can be changed by calling resolve() and Reject (). This will be fulfilled. If you call resolve(), the state of the current promise object will change to fulfilled. If you call Reject (), the state of the current promise object will change to Rejected.
const p = new Promise((resolve, reject) = > {
// Resolve (): Invoke the function, which will make the current promise object state change to depressing
Reject (): Calls the function reject(), which changes the state of the current Promise object to Rejected
resolve()
// reject()
})
console.dir(p)
Copy the code
Note: Changes to the promise state are one-time. This means that if you try to call the function multiple times to change the state of the current Promise object, the state of the current Promise object will only be affected by the function called the first time. Such as:
const p = new Promise((resolve, reject) = > {
resolve()
reject()
})
console.dir(p) // This is a big pity
Copy the code
Complement to the Promise state
The state of a promise does not change, that is, methods in THEN are not executed when the state of a promise is pending.
// If the state of the promise does not change, then methods will not be executed
new Promise((resolve, reject) = > {
}).then((value) = > {
console.log('success')},(reason) = > {
console.log('failure')})Copy the code
The result of a promise (received via a parameter)
If the function is not called, the result of the returned Promise object defaults to undefined; If a function is called and arguments are passed in the function, the result of the returned Promise object is the argument passed in the function.
const p = new Promise((resolve, reject) = > {
// Change the result of the current Promise object by calling resolve, passing the argument
resolve('Successful outcome')
//reject(' reject result ')
})
console.dir(p)
Copy the code
The prototype object method for Promise
Then method
There are two function arguments that are called on success and failure. The return value is also a Promise object. Regardless of the state of the Promise object before the THEN method, the state returned by the THEN method is pending, so you can make chain calls to the Promise method.
const p = new Promise((resolve, reject) = > {
// Change the result of the current Promise object by calling resolve, passing the argument
resolve('Successful outcome')
//reject(' reject result ')
})
// then method function
/ / parameters
// 1. Is a function
// 2. Also a function
// Return value: a Promise object
p.then(() = >{
// When the state of the promise is fulfilled, this will be fulfilled
console.log('Called on success')},() = > {
// Execute the promise whose state is Rejected
console.log('Called on failure')})console.dir(p) // Called when printing succeeds
Copy the code
const p = new Promise((resolve, reject) = > {
// Change the result of the current Promise object by calling resolve, passing the argument
//resolve('123')
reject('Result of failure')})// then method function
/ / parameters
// 1. Is a function
// 2. Also a function
// Return value: a Promise object
p.then((value) = >{
// When the state of the promise is fulfilled, this will be fulfilled
console.log('Called on success', value)
}, (err) = > {
// Execute the promise whose state is Rejected
console.log('Called on failure', err)
})
console.dir(p) // Print the result of a failure
Copy the code
A complement to the THEN method
The then method of a Promise object returns a promise in a pending state. So how do you change the state of this promise? Without further ado, on the code:
- Change the state from Pending to depressing
const p = new Promise((resolve, reject) = > {
// If the state of the promise does not change, then methods will not be implemented
// If the resolve() method is not called here, the success callback will not be called in the p.teng () method
// This, in turn, does not change the state returned by the then method of the Promise object
// Therefore, if you want to change the state returned by the then method of the Promise object, you must write this sentence
resolve()
})
const t = p.then((value) = > {
console.log('success')
// In a successful callback, use return to change the state of t instance from Pending to depressing and pass the parameters of success
// In the success callback of the returned Promise object, value can be used to receive the passed argument
return 123
}, (reason) = > {
console.log('failure')
})
t.then((value) = > {
console.log('2' success, value)
}, (reason) = > {
console.log('failure')})Copy the code
- Change the status from Pending to Rejected
If a code error occurs in the THEN method, the returned Promise instance is changed to the Rejected state
// If the state of the promise does not change, then methods will not be executed
const p = new Promise((resolve, reject) = > {
resolve()
})
const t = p.then((value) = > {
console.log('success')
// Use return to change the state of t instance to depressing
//return 123
// If this code fails, it will change the state of t instance to Rejected
console.log(a)
}, (reason) = > {
console.log('failure')
})
t.then((value) = > {
console.log('2' success, value)
}, (reason) = > {
console.log('failure', reason)
})
Copy the code
Catch method
1. The parameter function in catch fires when the state of the Promise object changes to Rejected.
2. The promise will also be executed if a code error occurs in the implementation body.
const p = new Promise((resolve, reject) = >{
// reject()
// console.log(a)
throw new Error('Wrong')})// Think: when is the argument function in catch executed?
// 1. When the state of the promise is rejected, it is implemented
// 2. If a code error occurs in the promise body, the promise will be executed
p.catch((reason) = > {
console.log('failure', reason)
})
console.log(p)
Copy the code
The most common way to write promise
As mentioned earlier, successful and failed callbacks can be received in the THEN method. But because of the catch method, the most common way to write this is to execute the success callback of a promise in the then method and the failure callback of a promise in the catch method.
new Promise((resolve, reject) = > {
})
.then((val) = > {
// Executed on success
console.log(val)
})
.catch((err) = > {
// Execute on failure
console.log(err)
})
Copy the code
All methods
The promise.all () method is used to wrap multiple Promise instances into a new Promise instance.
Const p = promise. all([p1, p2, p3]); // P1, p2, and p3 are all promise instances
Matters needing attention:
1.Promise.all() takes an array of Promise instances as arguments and returns a Promise. This means that you can use the then method after promise.all () to receive a success callback and the catch method to receive a failure callback.
2. Only when the state of the array of Promise instances is fulfilled, the successful callback after promise.all () will be executed. If there is a Promise instance array with a state of Rejected, the failure callback after Promise.all() is executed immediately, and the first Rejected callback is returned instead of the success callback.
- The result of a successful callback
let p1 = new Promise((resolve, reject) = > {
setTimeOut(resolve, 2000.'p1')})let p2 = new Promise((resolve, reject) = > {
setTimeOut(resolve, 1000.'p2')})let p3 = new Promise((resolve, reject) = > {
setTimeOut(resolve, 3000.'p3')})let pAll = Promise.all([p1, p2, p3])
pAll
.then(success= > {
console.log(success)
})
.catch(err= > {
console.log(err)
})
/ / return [" p1 "and" p2 ", "p3"]
// Returns an array
// The order of return values is the same as in the call order of the promise.all method, regardless of the speed of the asynchronous request.
Copy the code
- The result of a failed callback
let p1 = new Promise((resolve, reject) = > {
setTimeOut(reject, 2000.'p1')})let p2 = new Promise((resolve, reject) = > {
setTimeOut(resolve, 1000.'p2')})let p3 = new Promise((resolve, reject) = > {
setTimeOut(resolve, 3000.'p3')})let pAll = Promise.all([p1, p2, p3])
pAll
.then(success= > {
console.log(success)
})
.catch(err= > {
console.log(err)
})
// return p1
// If one promise fails, the callback that triggered the failure is returned, regardless of whether other promises have been fulfilled
Copy the code
Race method
This is written in much the same way as the All method, which returns a promise object. You can also continue to use the then method to trigger a success callback and the catch method to trigger a failure callback. Just remember one rule: whoever completes first is returned based on the status and result of completion.
Const p = promise.race ([p1, p2, p3]); // P1, p2, and p3 are all promise instances
Because it’s pretty much the same as all, I won’t bother here.
Promise on the back
I’ll find time to sort through handwritten Promise codes, custom Zoomout browsing components, global stabilization, skU attribute filtering, and shopping cart logic. I’ve never read through a VUE document until now. I have to force myself to read through and browse through vue documents (Vue buckets) and VUe-element-Admin documents multiple times, read vue source code, learn about tokens and AXIos encapsulation. It’s still a mess. There’s still a lot to learn.
Learning & Summarizing