I. overview
Promise is a solution for asynchronous programming, which can replace the traditional solution - callback functions and events. ES6 unifies usage and provides native promise objects. 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, that is, promise has only one state at any time.
II. Promise status
Promise has three statuses: * * Pending * *, * * Resolved * *, and Rejected * *. Promise starts from the Pending state. If successful, it will go to the successful state and execute the resolve callback function; If it fails, go to the failed state and execute the reject callback function. The following is the specification diagram of promise
III. basic usage
Promise objects can be created through promise's constructor.
var promise = new Promise(function(resolve,reject) setTimeout(function(){ console.log("hello world");},2000); });
The Promise constructor takes a function as a parameter. The two parameters of the function are resolve and reject, which are provided by the JavaScript engine. The resolve function is used to call resolve when the Promise object is transferred successfully and pass the operation result as its parameter; The reject function is used to pass the error reported by the operation as its parameter when the state of a single Promise object changes to failure. As shown in the following code:
function greet(){ var promise = new Promise(function(resolve,reject){ var greet = "hello world"; resolve(greet); }); return promise; } greet().then(v=>{ console.log(v);//* })
The output result of the * line above is the value of greet, that 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 take the Promise as the return value of the function.
then method of four Promise
the then method of promise has the following three parameters: success callback, failure callback and forward callback. Generally, only the first one needs to be implemented, and the latter is optional. The most important thing in promise is the state. The chain operation of callback function can be realized through the state transfer of then. Execute the following code first:
function greet(){ var promise = new Promise(function(resolve,reject){ var greet = "hello world"; resolve(greet); }); return promise; } var p = greet().then(v=>{ console.log(v); }) console.log(p);
The output of the modified program is:
It can be seen that the promise execution then is still a promise, and the promise execution is asynchronous, because hello world is printed in front of the last output statement, and the promise status is pending.
Because Promise is still Promise after then, you can continuously call the callback function in a chain according to this feature. Here is an example:
function greet() { let promise = new Promise((res, rej) => { let name = "Zhang San" res(name) }) return promise } greet().then(v => { console.log(v) return v+"2" //This value v+"2" is reserved for the v parameter of the next then }).then(v => { console.log(v) return v+"3" }).then(v => { console.log(v) })
result:
V. other methods of Promise
reject usage
The function of reject is to set the state of Promise from pending to rejected, so that the callback function of reject can be captured in then
function judgeNumber(num){ var promise1 = new Promise(function(resolve,reject){ num =5; if(num<5){ resolve("num Less than 5, the value is:"+num); }else{ reject("num Not less than 5, the value is:"+num); } }); return promise1; } judgeNumber().then( function(message){ console.log(message); }, function(message){ console.log(message); } )
After. then, there are two methods. The former one executes the parameter of the resolve callback and the latter one executes the parameter of the reject callback.
catch usage
function judgeNumber(num){ var promise1 = new Promise(function(resolve,reject){ num =5; if(num<5){ resolve("num Less than 5, the value is:"+num); }else{ reject("num Not less than 5, the value is:"+num); } }); return promise1; } judgeNumber().then( function(message){ console.log(message); } ) .catch(function(message){ console.log(message); })
At this time, catch executes the same as reject, that is, if the state of Promise changes to reject, it will be caught by catch. However, it should be noted that if the callback function of reject method is set earlier, · catch will not catch the state changing to reject. Another difference of catch is that if an error occurs in resolve or reject, it will be caught by catch, which is the same as the error handling in java and c + +, so as to avoid the program getting stuck in the callback function.
all usage
Promise's all method provides the ability to execute asynchronous operations in parallel. The callback is executed only after all asynchronous operations in all are completed.
function p1(){ var promise1 = new Promise(function(resolve,reject){ console.log("p1 First output statement of"); console.log("p1 Second output statement of"); resolve("p1 complete"); }) return promise1; } function p2(){ var promise2 = new Promise(function(resolve,reject){ console.log("p2 First output statement of"); setTimeout(()=>{console.log("p2 Second output statement of");resolve("p2 complete")},2000); }) return promise2; } function p3(){ var promise3 = new Promise(function(resolve,reject){ console.log("p3 First output statement of"); console.log("p3 Second output statement of"); resolve("p3 complete") }); return promise3; } Promise.all([p1(),p2(),p3()]).then(function(data){ console.log(data); })
The operation results are as follows:
Here you can see that p2's resolve is put into a setTimeout, and the final. then will not be executed until all Promise state changes are completed.
race usage
in the callback function in all, wait until all promises are executed, and then execute the callback function. Race is different. It starts to execute the callback function when the first Promise changes state. Change the above all to race to get
Promise.race([p1(),p2(),p3()]).then(function(data){ console.log(data); })
The operation results are as follows:
The words "p1 complete" are circled in the red box, indicating that only the state of the first promise changes when the then() method is executed.
Another problem to note here is that promise is executed asynchronously, such as the following:
var i var promise = new Promise(function(resolve,reject){ resolve("hello"); }) promise.then(data=>{ i = 2; }) console.log(i);
The result is undefined, not because promise cannot change the external value, but because the then() method is not finished when console.log(i) is executed. If you delay the output of console.log(i), you can get the correct results:
setTimeout(()=>console.log(i),1000);
So don't execute some code that depends on promise changes after promise, because the code in promise may not be executed completely, or you can delay its output.
If my content can help you, I will be very happy!