1. What is promise?
Promise is a solution to asynchronous programming. Asynchronous operations can be queued, executed in the desired order, and returned as expected.
Syntactically, a promise is an object from which to get messages for asynchronous operations;
In its original sense, it is a promise that will give you results over time.
2. Why are there promises
In general, we don’t see a lot of callback nesting, usually one or two levels, but in some cases, when a lot of callback nesting, the code can be very cumbersome, which can cause a lot of trouble in our programming. This situation is commonly known as callback hell.
3. The use of promises is related
Promise has three states: pending, fulfiled, and Rejected. Once the state has changed, it will never change. Once a Promise instance is created, it executes immediately.
Promise to create
Var promise = new promise (function(resolve, reject) {resolve, reject});Copy the code
The chain operation
Then () success
The catch () failure
.race() continues with a return
.all() All returns continue
4. Advantages and disadvantages of promises
Advantages: With the Promise object, asynchronous operations can be expressed as a flow of synchronous operations, eliminating layers of nested callback functions. In addition, Promise objects provide a unified interface that makes it easier to control asynchronous operations.
Disadvantages: First, there is no way to cancel a Promise; once it is created, it is executed immediately and cannot be cancelled halfway through. Second, if you don’t set a callback function, errors thrown inside a Promise won’t be reflected externally. Third, when you are in a Pending state, you have no way of knowing what stage of progress you are currently in (just beginning or just finishing).
5. Actual combat
// getLegend() {return new Promise((resolve, reject) =>{const params = {output: 'extend', itemids: '1111' } this.$util.axios({ method: '/getHost', Params}).then(res => {resolve(res)}).catch(err => {reject(err)})})} console.log(res) })Copy the code