Reading notes-you don't know JS in-promise (2)

Source: Internet
Author: User

Keep pits.

Mode

Consider the following code:

    function fn (x) {        //dosomething        returnnew Promise (function  (Resolve, Reject) {            // Call Resolve (..) and reject (...)         });    }     var p = fn (2);

  New Promise (..) Patterns are often referred to as revealing constructor. The incoming function executes immediately (not like then (..) The callback in the same asynchronous delay), it has two parameters, resolve and reject, respectively. These are promise's resolution functions. The resolve is usually identified as complete, and the Reject identity is rejected.

Duck type

How to tell if an object is not a promise? Although Promise is through new Promise (..) Created, but cannot be detected by instanceof promise, the main reason is that promise may come from other windows, checking that such promise instances are not recognized.

The method of identifying promise is defined to have the then method. That is, any object and function, if there is a then (including the prototype chain) method, is considered to be a promise object.

The logic is probably as follows:

    if (        null &&        (typeoftypeof p = = = ' function ') &&        typeof P.then = = = ' function '    ) {        // This is a Promise object    }

Promise Features

1. When you call then on a promise, the provided callback will always be called asynchronously.

2, as long as the promise is resolved, the callback provided to then will be automatically called, always return a value.

Promise and competing states

Although it is said that once promise is resolved, the callback of the subsequent then method must be called, but the resolution itself is not executed and can only be enforced by another mechanism:

    //must return a promise    functionDelay (time) {return NewPromise (function(Resolve, Reject) {SetTimeout (function() {Reject (' Time Out ');        }, time);    }); }    //in 3 seconds, no resolution will be reject .Promise.race (P, delay). Then (function() {        //Success},function(err) {//failed})

  

Promise Exception

  Consider the following code:

    varp =NewPromise (function(Resolve, reject) {//Exceptionfo (); }) P.then (function(data) {Console.log (data); }, function() {        //The reject accepted the exception and made an exception.foo (); }). Then (function() {    }, function() {        //This reject handles the last exception.Console.log (1); });

  As you can see, each then method returns a promise, and once the resolution does not change, the exception is transferred to the next then reject.

Promise's Callback

  It seems that promise is also using callback functions to complete asynchronous operations, but there are some differences.

About Promise.resolve (..)

If (..) to Promise.resolve Passing an immediate value of a non-promise, non-thenable (that is, an object or function that has a then method), you get a promise with this value in the blanks, which is equivalent to packing.

In the following two cases, P1 and P2 behave the same way:

    var New Promise (function(resolve, reject) {        resolve;    });     var = promise.resolve (P2);     // Promise {[[Promisestatus]]: "Resolved", [[Promisevalue]]:

And if (..) to Promise.resolve, Passing a real promise will only return the same promise.

    var = Promise.resolve (P1);     var p2 = promise.resolve (p1);     // true

  If (..) to Promise.resolve A non-promise thenable value is passed, the former attempts to expand the value, and the unwind process continues until the final value of a specific non-class promise is extracted.

For example:

    var p = {        function(resolve, reject) {            resolve ();             // reject (' 123 ');         }    };    P.then (function  Resolve (val) {        console.log (val);     function reject (Err) {        console.log (err);    });     //Print 42 get a promise

 Promise.resolve (..) You can accept any thenable and unpack it as a non-thenable value. From Promise.resolve (..) The obtained affirmation is a promise, which is a trustworthy value.

Encapsulate an unknown tool promise and parse it, so you can:

    Promise.resolve (' tool '). Then (function(val) {        console.log (val);    });

In this way, all unknowns can be encapsulated as promise, guaranteeing asynchronous invocation.

Chained calls

Multiple promise can be connected together to represent a series of asynchronous steps:

1. Each time you call then (..), it will create and return a new promise that we can link together.

2, no matter from then (..) The value returned by the completion callback of the call will be set to be linked promise.

Don't know well:

    var p = promise.resolve (2);     var p2 = p.then (function(v) {        //2        return v * 2;    });    P2.then (function(v) {        //4    });

2 is encapsulated by Promise.resolve, and the first then method is called to get data 2. It then returns a Promise wrapper object containing 4, which is obtained by calling the then method to 4.

As long as the return and then method is used, the promise chain call can be implemented.

Ajax case

Chained calls can be perfectly combined with Ajax, as in the following example:

    //hypothesis Existence Method Ajax (Url,callback)    functionrequest (URL) {return NewPromise (function(Resolve, reject) {//The callback function of Ajax is Promise's resolve () functionAjax (URL, resolve);    }); }    //asynchronous request returns dataRequest (' http://... '). Then (function(data) {//stitching the returned data to the second URL as a parameter request again        returnRequest (' Http://...?data= ' +data); }). Then (function(data2) {//get the final dataConsole.log (DATA2); });

 If the then method parameter does not provide resolve or reject, a default function is generated, as in the following example:

Promise.resolve (2). Then (//function (v) {        //return v;        //}        NULL,        function() {Console.log (1); }). Then (function(v) {console.log (v);//2        },        //default error handling function        //function (err) {        //throw err;        //});

 Summary: 1, call Promise.resolve (..) and then (..) Always returns a promise.

2, the value returned after the resolution can be resolved by chaining the call.

  

Reading notes-you don't know JS in-promise (2)

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.