Promise is the solution to asynchronous task synchronization? This article introduces Promise through the following aspects:
- What problem did Promise come along to solve
- Internal processing of a task within a Promise
- The standard specification for Promises
- Use the Promise method
- The Promise executes the order in the eventLoop
- The source address
Promise knowledge is divided into five chapters. In this chapter, we discuss the internal processing of tasks in promises. As mentioned above, the Promise state can only be changed once, which can solve the trust problem. Let’s talk about what states are in promises and how they relate to callbacks.
Three states
This is a big pity. Phase-out process (which is very disappointing) 3. Phase-out process (which is very disappointing)
new Promise((resolve,reject) = >{
setTimeout(() = >{
resolve('MY status has changed from Pendding to Resolved')},1000)
reject('My status changes from Pendding to Rejected')
}).then(response= >{
console.log('I'm a successful callback.',response) // I have successfully changed my state from Pendding to Resolved
}).catch(err= >{
console.log('I'm a failed callback.',err) // My status changes from Pendding to Rejected
})
Copy the code
Of course, this example does not go to a successful callback, because in Promise the pending state does not change again when it changes to Rejected, which is why it can solve the trust problem (there will be an answer whether it succeeds or fails). To recap: Resolve is passed as an argument when the task calls resolve state from pending => Resolved and fires the. Then callback. Reject is called from pending => Reject and a. Catch or. Then callback is triggered. Reject is passed as a parameter. Typically, promises encapsulate asynchrony, allowing it to execute internally uniformly, giving a specified result. This is the solution to asynchronous task synchronization. In practice, asynchronous tasks have three states: pending for a network request or an unscheduled timer. Fulfill (Fulfill) : Fulfill (Fulfill) : Fulfill (Fulfill) : Fulfill (Fulfill) : Fulfill (Fulfill)) : Fulfill (Fulfill) : Fulfill (Fulfill)) Reject state. When a request times out or fails, we call reject and call back catch().
If this article can help or inspire you, it will be my pleasure