1. Overview
Promise is a solution for asynchronous programming that can replace traditional solutions - callback functions and events.
ES6 unifies usage and provides a Promise object natively.
As an object, Promise has the following two characteristics:
- (1) The state of the object is not affected by the outside world.
- (2) Once the state changes, it will not change again, which means that there is only one state for Promise at any time.
2. The status of the promise
Promise has three states, namely Pending (in progress), Resolved (completed), and Rejected (failed).
Promise starts from the Pending state, if successful, it goes to the success state, and executes the resolve callback function; if failed, it goes to the failed state and executes the reject callback function.
3. Basic usage
Promise objects can be created through the Promise constructor
var promise = new Promise((resolve,reject) => { setTimeout(()=>{ ("hello world") }, 2000) })
The Promise constructor accepts a function as an argument, and the two arguments of the function are resolve , reject , which are provided by the JavaScript engine.
The function of the resolve function is to call resolve when the Promise object is transferred to successfully, and pass the operation result as its parameters; the function of the reject function is to pass the error reported by the operation as parameters when the state of the Promise object becomes failure.
The following code:
function greet(){ var promise = new Promise(function(resolve,reject){ var greet = "hello world" resolve(greet) }) return promise } greet().then(v=>{ (v)//* })
The output of the * line above is the value of greet, which is the parameter passed by resolve().
Note: Creating a Promise object will immediately execute the code inside, so in order to better control the running time of the code, you can include it in a function and use this Promise as the return value of the function.
4. Promise then method
The then method of promise has the following three parameters: successful callback, failed callback, and forward callback.
Generally, only the first one needs to be implemented, and the latter one is optional.
The most important state in Promise is the implementation of chain operation of callback function that can be realized through then state transfer.
First execute the following code:
function greet () { var promise = new Promise (function(resolve, reject){ var greet = "hello world" resolve(greet) }) return promise } var p = greet().then(v => { (v) // Promise { <pending> } }) (p) // hello world
From this we can see that the promise execution then is a promise, and the execution of the promise is asynchronous.
Because hello world is printed out before the last output statement, and the status of the Promise is pending (in progress).
Because Promise is still Promise after executing then, you can continuously call callback functions in a chain according to this feature.
Here is an example:
function greet () { var promise = new Promise(function (resolve, reject){ var greeet = "hello world" resolve(greet) }) return promise } greet().then(v => { (v+1) return v }) .then (v => { (v+2) return v }) .then (v => { (v+3) })
V. Other methods of Promise
reject usage
The function of reject is to set the state of the promise from pending to rejected, so that the callback function of reject can be captured in then
function judgeNumber (num) { var promise = new Promise (function(resolve, reject) { num = 5 if(num < 5){ resolve("num is less than 5, the value is" + num) } else { reject("num is not less than 5, the value is" + num) } }) return promise } judgeNumber().then( function (message) { (message) }, funtion (message) { (message) } )
.then contains two methods: the parameter of the previous one executing the resolve callback and the parameter of the latter executing the reject callback
Usage of catch
function judgeNumber(num){ var promise1 = new Promise(function(resolve,reject){ num =5; if(num<5){ resolve("num is less than 5, the value is:"+num); }else{ reject("num is not less than 5, the value is:"+num); } }); return promise1; } judgeNumber().then( function(message){ (message); } ) .catch(function(message){ (message); })
At this time, the catch executes the same as reject, that is, if the state of the Promise becomes reject, it will be caught by the catch. However, it should be noted that if the callback function of the reject method is set before, the catch will not catch the situation where the state becomes reject.
The other difference between catch is that if an error occurs in resolve or reject, it will be caught by catch, which is the same as when handling errors in Java and C++, so that the program can be avoided from being stuck in the callback function.
All Usage
The all method of Promise provides the ability to perform asynchronous operations in parallel, and callbacks are executed only after all asynchronous operations are completed.
function p1(){ var promise1 = new Promise(function(resolve,reject){ ("The first output statement of p1"); ("The second output statement of p1"); resolve("p1 completed"); }) return promise1; } function p2(){ var promise2 = new Promise(function(resolve,reject){ ("The first output statement of p2"); setTimeout(()=>{("The second output statement of p2");resolve("p2 completed")},2000); }) return promise2; } function p3(){ var promise3 = new Promise(function(resolve,reject){ ("The first output statement of p3"); ("The second output statement of p3"); resolve("p3 completed") }); return promise3; } ([p1(),p2(),p3()]).then(function(data){ (data); })
Race usage
In the callback function in all, wait until all the promises are executed, and then execute the callback function. Race is different. It will wait until the first promise changes state and start executing the callback function.
Change the above `all` to `race` and get
([p1(),p2(),p3()]).then(function(data){ (data); })
There is another issue that needs to be noted here. The execution of promises is asynchronous, such as the following:
var i var promise = new Promise(function(resolve,reject){ resolve("hello"); }) (data=>{ i = 2; }) (i);
The result is undefined, not because promise cannot change the external value, but because when (i), then() method has not been executed yet.
If you delay the output (i) you can get the correct result:
setTimeout(()=>(i),1000);
So don't execute some code after the promise that depends on the promise change, because the code in the promise may not be executed, or you can delay the output.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.