Overview
It is a solution for asynchronous programming.
Syntactically speaking, Promise is an object from which you can obtain messages about asynchronous operations.
Promise States
Characteristics of States
Promise asynchronous operations have three states: pending (in progress), fulfilled (succeeded), and rejected (failed). Except for the result of the asynchronous operation, no other operation can change this state.
Promise objects only have state transitions: from pending to fulfilled and from pending to rejected. Once in the fulfilled or rejected state, the state will no longer change, that is, resolved (settled).
Disadvantages of States
Promise cannot be canceled. Once it is created, it executes immediately and cannot be canceled midway.
If no callback function is set, errors thrown inside Promise will not be reflected externally.
When in the pending state, it is impossible to know which stage the current progress is at (just started or about to complete).
then Method
The then method accepts two functions as parameters. The first parameter is a callback for when the Promise executes successfully, and the second parameter is a callback for when the Promise fails. Only one of the two functions will be called.
Characteristics of the then Method
The callback function will not be called until the current run of the JavaScript event queue completes.
Through.thencallback functions added in the form will be called no matter when.
By calling multiple times
The then method returns a Promise object in the resolved or rejected state for chained calls, and the value of the Promise object is this return value.
Points to Note about the then Method
For simple Promise chain programming, it is best to keep it flat and avoid nesting Promises.
Always remember to return or terminate a Promise chain.
When you create a new Promise but forget to return it, the corresponding chain is broken, causing p4 to proceed simultaneously with p2 and p3.
For rejections in a Promise chain that cannot be terminated in most browsers, it is recommended to always follow with.catch(error => console.log(error));