1.Promise Introduction
Promise is the first community proposed and implemented, the latter ES6 to write to the standard, and the original Promise object, is an asynchronous programming solution, the specific concept you can go to view the relevant information. Traditionally, handling asynchrony is done in the form of a callback callback function, but when the callback is nested too much, it makes the program difficult to understand, as shown below
function A (CB) { console.log (' a ... '); CB (' a ');} function B (CB) { console.log (' B ... '); CB (' B ');} function C (CB) { console.log (' C ... '); CB (' c '= = B (() = C (() = {})); A...b...c ...
If there is logic behind the output of the C function, the callback will be a big annoyance.
Using promise to handle this asynchronous callback will be very intuitive, promise asynchronous processing with synchronous operations, as shown below
functionA () {Console.log (' A ... '); return' A output ';}functionB (res) {Console.log (' B ... '); Console.log (' Get A: ' +res); return"B Output";}functionC (Res) {Console.log (' C ... '); Console.log (' Get B: ' +res);}NewPromise (Resolve,reject) = {SetTimeout (resolve,1000)}). Then (a), then (b). then (c); Promise {<state>: "Pending"}a...b...get a:a outputc...get b:b output
Usage of 2.Promise
Promise is a constructor that receives a function parameter that receives two functions as arguments, respectively, as Resolve,reject. These two functions are provided by promise themselves and do not need to be deployed on their own. The resolve function shifts the state of promise from ' Pending ' to ' resolved ', and the Reject function shifts the state from ' Pending ' to ' rejected '.
The basic syntax, as shown below
New Promise ((resolve,reject) = { if// Asynchronous processing succeeded Resolve (); } Else { reject (); }}). Then (onfulfilled,onrejected);
Create a promise instance, as shown below
var New Promise (Resolve,reject) = {console.log (' hehe '); Resolve (' resolved '= Console.log (val)) Console.log (' current '); hehecurrentresolved
The resolve function and the Reject function call can pass parameters, generally to the Reject function passed an instance of error, to indicate the thrown error, the parameters passed to the Reject function can be a general value, or it can be an instance of promise, At this point the instance state of the promise is determined by the state of the parameter promise instance, as shown below
var New Promise ((resolve,reject) = { setTimeout (()=>{console.log (' P1 ' after 1 seconds); resolve (p2);},1000);}); var New Promise ((resolve,reject) ={ setTimeout (()=>{console.log (' P2 ' after 2 seconds); Resolve (' P2 ');},2000) ;}); P1.then (val)=<state>: "Pending" }1 seconds after p12 seconds p2p2
As shown above, promise is created immediately, and then the callback function of the then method executes the execution of all the synchronization statements in the current script, but is higher than the queue priority of the timer, as shown below
setTimeout (() =>console.log (' settimeouting ... '), 0); var promise = {Console.log ( ' promise constructing ... ' ); Reject ( new error (' ERROR ' null , (reason) => <state>: "Pending" }error:error stack trace: Promise <@debugger eval code:4:9@ debugger eval code:2:15settimeouting ...
Promise's prototype method then, the method adds a callback function for the promise instance when the state changes, the first parameter is the callback when the state is resolved, and the second parameter is a callback with a status of rejected. As shown below
var New Promise (resolve,reject) = { console.log (' p3 '); Resolve (' P3 ');}); var New Promise (resolve,reject) = { console.log (' P4 '); SetTimeout (()=>resolve (' P4 '), ();}); P3.then (()=>p4). Then (Result) =<state>: "Pending" }P4
Promise internal errors are not captured (except for Chrome), unless the Catch method is used, and if thrown before resolve, the resolve does not execute, instead it is equivalent to no throw error, as shown below
varPromise =NewPromise ((resolve,reject) ={Console.log (' Promise constructing ... '); Throw NewError (' ERROR '); Resolve (' Haha ');}); Promise.then (val)=Console.log (val));p romise constructing ...-------------------------------------------------------------varPromise =NewPromise ((resolve,reject) ={Console.log (' Promise constructing ... '); Resolve (' Haha '); Throw NewError (' ERROR '); });p Romise.then (val)=Console.log (val));p romise constructing ...haha
Using Promise's prototype method, catch catches the error, which is actually the. then (Null,reject) alias, as shown below
var promise = new Promise ((Resolve, Reject) => {Console.log ( ' promise constructing ... ' ); throw new error (' ERROR ' ); Resolve ( ' haha ' =>console.log (val)). catch (error) =>console.log (Error);p romise constructing ... Promise { <state>: "Pending" }error:error stack trace: Promise <@debugger eval code:3:8@ debugger eval code:1:19
Promise error capture You can use the second parameter of the then method to specify the callback function for the Reject. You can also use the Promise.prototype.catch method to capture, but it is generally recommended to use method two, because catch captures not only the errors that are thrown inside the promise, but also the errors in the then method. However, after calling the Resolve method, the error will not be caught, which is equivalent to no throw error, as shown below
varPromise =NewPromise ((resolve,reject) = { Throw NewError (' Promise error ');}); Promise.then (NULL, (err) = =Console.log (err)); Promise {<state>: "Pending"}error:promise Error Stack trace: Promise<@DebuggerEval Code:2:9@DebuggerEval code:1:19---------------------------CatchMethod-------------------varPromise =NewPromise ((resolve,reject) ={Reject (NewError (' Promise error '));}); Promise.Catch(Error) =Console.log (Error)); Promise {<state>: "Pending"}error:promise Error Stack trace: Promise<@DebuggerEval Code:2:9@DebuggerEval code:1:19---------------------------then method error-------------------varP5 =NewPromise ((resolve,reject) ={Resolve (' Hehe ');}); P5.then (val)=>VAL+X).Catch(ERR) =Console.log (err)); Promise {<state>: "Pending"}referenceerror:x is not defined stack trace: @DebuggerEval code:4:16
The Catch method also returns a promise, so the chained method can then be used after the catch, but then the error of the method will not be captured by the previous catch, as shown below
var New Promise ((resolve,reject) = { resolve (' hehe ');}); P5.then ((val)=>val+x). Catch (err) =>console.log (ERR)). Then (Val) =>y+3<state>: "Pending" }referenceerror:x was not Defined stack trace: @Debugger eval code:4:16
3.promise.all
The Promise.all method can combine multiple Promise instances [p1,p2,p3 ...] Packaged into a Promise object A,a state by p1,p2,p3 ... Decision: If P1,p2,p3 ... The state of the onfulfilled,a becomes onfulfilled, and p1,p2,p3 ... The result of the asynchronous operation consists of an array passed to the callback function; p1,p2,p3 A status of Rejected,a becomes rejected immediately, and the return value of the first rejected is passed to the callback function, as shown below
varP1 =NewPromise ((resolve,reject) ={Console.log (' P1 ... '); SetTimeout (()=>resolve (' P1 resolved ... '), 1000);});varP2 =NewPromise ((resolve,reject) ={Console.log (' P2 ... '); SetTimeout (()=>resolve (' P2 resolved ... '), 2000);});varP3 =NewPromise ((resolve,reject) ={Console.log (' P3 ... '); SetTimeout (()=>resolve (' P3 resolved ... '), 3000);}); Promise.all ([P1,P2,P3]). Then (args)=>{console.log (' 3S output after: '); for(let V of args) {Console.log (v);}}); P1...p2...p3 ... Output after 3S: P1 resolved...p2 resolved...p3 resolved ...------------------------a promise instance becomes rejected---------------varP1 =NewPromise ((resolve,reject) ={Console.log (' P1 ... '); SetTimeout (()=>resolve (' P1 resolved ... '), 1000);});varP2 =NewPromise ((resolve,reject) ={Console.log (' P2 ... '); SetTimeout (()=>resolve (' P2 resolved ... '), 2000);});varP3 =NewPromise ((resolve,reject) ={Console.log (' P3 ... '); SetTimeout (()=>resolve (' P3 resolved ... '), 3000);});varP4 =NewPromise ((resolve,reject) ={Console.log (' P4 ... '); Reject ("P4 rejected ...");}); Promise.all ([P1,P2,P3,P4]). Then (args)=>console.log (args), (reason) =console.log (reason));p 1...p2...p3...p4 ... Promise {<state>: "Pending"}P4 rejected ...
4.promise.race
As with Promise.all, the method also will be multiple promise instances [P1,P2,P3 ...] Packaged into a new promise instance B. The literal meaning of "race" is competition, so [p1,p2,p3 ...] Whose state changes first, the state of B immediately changes the same state and the return value of the first promise instance that changes the state is passed to the callback function, as shown below
varP1 =NewPromise ((resolve,reject) ={Console.log (' P1 ... '); SetTimeout (()=>resolve (' P1 resolved ... '), 1000);});varP2 =NewPromise ((resolve,reject) ={Console.log (' P2 ... '); SetTimeout (()=>resolve (' P2 resolved ... '), 2000);});varP3 =NewPromise ((resolve,reject) ={Console.log (' P3 ... '); SetTimeout (()=>resolve (' P3 resolved ... '), 3000);}); Promise.race ([P1,P2,P3]). Then (Val)=>console.log (Val), (reason) =console.log (reason));p 1...p2...p3 ... Promise {<state>: "Pending"}p1 resolved ...
5.promise.resolve and Promise.reject
Promise.resolve is the conversion of a given parameter into a Promise object, as shown below
Promise.resolve (ARG); // equivalent to New Promise ((resolve) =>resolve (ARG))omise.resolve (' resolve convert ... '). Then (val) = <state>: "Pending" }resolve convert ...
The promise.resolve has different actions depending on the given parameter type:
A, the argument is a promise instance, the instance is returned directly
B, the parameter is empty, execute a new promise instance that returns a resolved state
C, the parameter is a normal numeric value or object, then return a new promise instance of the resolved state directly, as shown below
Promise.resolve ({x:1}). Then (val) =<state>: "Pending"1}
D, the parameter is the Thenable object, both the object implements the then method, when a new promise instance is returned and immediately executes the object then method, as shown below
var thenableobj = {then (resolve,reject) { reject (' test ... ');} }; Promise.resolve (thenableobj). Then (null, (reason) =<state>: "Pending" }test ...
Promise.reject is consistent with promise.resolve, except that the status of the Promise instance returned is rejected, as shown below
Promise.reject (' Reject convert ... '). Then (null, (reason) =<state>: "Pending" }reject Convert ...
6. Extend the method to the native promise object, as shown below
//a little bit two functions from Raunyifeng blogPromise.prototype.done =function(onfulfilled, onrejected) { This. Then (onfulfilled, onrejected).Catch(function(reason) {setTimeout ()= = {ThrowReason}, 0); });}; This method can capture error Promise.prototype in the previous call chain as long as it executes.finally=function(callback) {Let P= This. Constructor; return This. Then (value= P.resolve (callback ()). then (() =value), Reason= P.resolve (callback ()). then (() = {Throwreason}) );}; This method executes the callback function regardless of whether the state of the promise instance is changed .
Es6-note5:promise