Javascript-promise Object

Source: Internet
Author: User

Advantages:
  1. 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)
  2. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.