Promise is used to solve the problem of callback hell
1. Promise has three states: (life cycle)
- pending initial state
- fulfilled success status
- rejected failed status
Promise starts its life cycle from the moment it is new (the state of Promise will be reflected in [[PromiseStatus]]). The initial state is called Pending, which means that the asynchronous operation is in the pending period, indicating that the asynchronous operation has not been completed. Once the asynchronous operation is completed, the Promise is considered to be in the settled state, and will enter one of the following two states:
1.fulfilled (completed): Indicates that the asynchronous operation ended successfully;
2.rejected (rejected): Indicates that the asynchronous operation did not end successfully, and an error may have occurred during the period.
2, Promise method
- then method
The then method exists on all Promise objects and takes two parameters. The first parameter is the calling function whose Promise status is fulfilled (successfully ended), and the second is the calling function whose status is rejected (unsuccessfully ended).
promise.then(res => {
console.log(res)
},err => {
console.error(err)
})
//也可以进行链式操作
promise.then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
- catch method
promise.catch(err => {
console.log(err) })
// 等同于
promise.then(null,err => {
console.error(err)
})
- all() method
Promiss handles multiple concurrent requests, and is used when the same page needs to wait for two or more ajax requests to return data before it can be displayed normally!
let p1 = Promise.resolve(1), p2 = Promise.resolve(22), p3 = Promise.resolve(333);
let loading = true;
// 比方说加loading就可以加一个了 写个伪代码
Promise.all([p1,p2,p3]).then(res => {
console.log(res) // [1, 22, 333]
loading = false //伪代码
})
The order of returned data here is based on the order of the promise objects passed in. If one of them rejects, the following code will stop immediately and return the error information to the catch
- race() method
Take out the request with the fastest response, regardless of whether the result itself is successful or failed
let p1 = Promise.resolve(1), p2 = Promise.resolve(22), p3 = Promise.resolve(333);
Promise.race([p1,p2,p3]).then(res => {
console.log(res) // 1
})
Detailed explanation of promise principle