Advantages:
- In the process of asynchronous execution, the code that executes the code and the result is clearly separated (because the Promise object has a chained notation, then and catch)
- Combined with promise, many asynchronous tasks can be combined in parallel and serially.
Example 1. Generates a random number between 0-2 and, if less than 1, waits for a period of time to return successfully, otherwise the return fails:
' use strict ';//Clear log:varLogging= Document.getElementById(' Test-promise-log '); while(Logging.Children.length > 1){ Logging.RemoveChild(Logging.Children[Logging.Children.length - 1]);}//output log to page:function Log(s){ varP= Document.createelement(' P '); P.InnerHTML =S; Logging.appendchild(p);}New Promise(function(Resolve,Reject{ Log(' Start new Promise ... '); varTimeOut= Math.Random()* 2; Log(' Set timeout to: ' +TimeOut+ ' seconds. '); SetTimeout(function(){ if(TimeOut< 1){ Log(' Call Resolve (... ')); Resolve(' OK '); } Else { Log(' Call reject (... ')); Reject(' timeout in ' +TimeOut+ ' seconds. '); } },TimeOut* +);}). Then(function(r){ Log(' Done: ' +R;}).Catch(function(reason){ Log(' Failed: ' +Reason;});
Example 2. To perform several asynchronous tasks serially, you need to do task 1 first, if you are successful and then do Task 2, and so on, any task failure will no longer continue and execute the error handler function. (Chained notation)
job1.then(job2).then(job3).catch(handleError);
Among them, Job1, JOB2 and JOB3 are all promise objects.
Example 3. Executes in parallel, executing P1 and P2, and then executing after they are all done then:
varP1= New Promise(function(Resolve,Reject{ SetTimeout(Resolve, -, ' P1 ');});varP2= New Promise(function(Resolve,Reject{ SetTimeout(Resolve, -, ' P2 ');});P1 and P2 are executed at the same time, and then after they are complete:Promise. All([P1,P2]). Then(function(results){ Console.Log(results); //Get an array: [' P1 ', ' P2 ']});
Example 4. Parallel execution, get the results returned first
varP1= New Promise(function(Resolve,Reject{ SetTimeout(Resolve, -, ' P1 ');});varP2= New Promise(function(Resolve,Reject{ SetTimeout(Resolve, -, ' P2 ');});Promise.Race([P1,P2]). Then(function(Result){ Console.Log(Result); //' P1 '});
Javascript-promise Object