es6 asynchronous request has three states: 1. pending (waiting state), then and catch will not be triggered; 2. fulfill (satisfied state), when resolve is actively called back, it will be in this state and will Callback then(); 3. reject (rejection status) will trigger the subsequent catch callback function.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Promise is a solution for asynchronous programming:
1. Mainly used for asynchronous calculations
2. Asynchronous operations can be queued. Execute in the expected order and return expected results
3. Promises can be passed and manipulated between objects to help us process the queue
Promise has three states:
1. pending[pending] initial state
2. fulfilled[implemented] operation successful
3.rejected[rejected] operation failed
When When the promise status changes, the response function in then() will be triggered to process subsequent steps; .
The state of the Promise object changes. There are only two promise states. Once the state changes, there will be no more variations: from pending to fulfilled
From pending to rejected.
As long as these two situations occur, the status will be solidified and will not change again.
Look at the picture below
What is printed is the resolve status, which triggers the callback of resolve transition
Look at the following picture
If an error is reported, return the promise in the promise state and trigger the catch callback. As long as there is an error, if there is a
.then, it will not be executed and only .catch will be executed.
Look at the following again
No error promise object is thrown, it is still in the resolve state
Finally look at the following picture
As long as the wrong promise object is thrown, it is in the reject state
Output the order of 1, 2, and 3 below
Question 1:Print out in order 1 3, 2 will not be printed because catch will not be executed (the promise of.then is in the resolve state and catchwill not be executed)
Question 2: Return 1 2 3, because When printing 1, an error object is thrown. It returns a promise in the reject state, and enters the reject state. However, .catch is a promise in the resolve state, so .then is executed again, and finally a resolve state is returned. The following promise
Promise.all method is used to wrap multiple Promise instances into a new Promise instance .
Promise.all(iterator)Promise.all([ new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve('result1') },2000) }), new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve('result2') },1000) })]).then(results =>{ results[0] results[1] console.log(results)})
【Recommended learning:javascript advanced tutorial】
The above is the detailed content of What are the three states of es6 asynchronous request?. For more information, please follow other related articles on the PHP Chinese website!