JavaScript: Understanding the Promise Method

Source: Internet
Author: User

What is promise?

The core idea of promise is to represent a result of an asynchronous operation, and promise has three states (pending initial state, fulfilled success state, rejected failure state). We can understand that the use of promise can implement non-blocking IO function, according to three different states, we can know the callback function implementation in which process.

Promise.prototype.then

SOURCE Analysis:

1  This. then =function(onfulfilled) {2     if(typeofonfulfilled!== "function")return  This;3     return NewPromise (function(Resolve, reject) {4Asapfunction() {5         Try {6 Resolve (onfulfilled (value));7}Catch(ex) {8 reject (ex);9         }Ten       }); One     }); A }; -  -  This. then =function(onfulfilled, onrejected) { the     return NewSelf.constructor (function(Resolve, reject) { -HandleNewHandler (onfulfilled, onrejected, Resolve, Reject)); -     }); - }; +  -Valuepromise.prototype = Promise.prototype;

We know. Then the method is implemented as an object's property, followed by an inherited method, so the then method can have a parameter. Then (onfulfilled), and can have two parameters. Then (onfulfilled,onrejected) , the first argument is the successful callback function, and the second parameter is the callback function that failed, and then from the handle method above you can see that then the two parameters are stored in a queue (deferreds) as an array object, and then the then method is processed from the queue.

. Then chained calls

Example (just because the non-chained each time is promise iteration only):

1 //Create a new function that returns a Promise object2 varP1 =functionConstructorpromise (a) {3   return NewPromise (function(Resolve, reject) {4Resolve (1)5   });6 }7 8 //implementing chained calls9 varcon = constructorpromise (2)Ten Con One. Then (function(a) { A   varFirst = Document.getelementsbyclassname (' part-second ') [0] -First.innertext =a -   returnA + 2 the }) -. Then (function(b) { -   varFirst = Document.getelementsbyclassname (' part-first ') [0] -First.innertext =b +})

Note that there are two then method implementations of the callback, the first then method function call argument is from promise resolve callback passed in the parameter value 1, The function call pass of the second then method is the value 3 (return a +2) passed down from the last then method function, so the parameter of the second function obtains the result of 3. (Remember: If it is a chained call then, the parameter from the second then function is the result returned from the last then function, if the previous then did not return, Then the function parameter for the next then is undefined)

Promise.all ()

SOURCE Analysis:

1Promise.all =function(arr) {2       varargs =Array.prototype.slice.call (arr);3       return NewPromise (function(Resolve, reject) {4         if(Args.length = = 0)returnresolve ([]);5         varRemaining =args.length;6         functionRes (I, Val) {7           Try {8             if(Val && (typeofval = = = "Object" | |typeofval = = = "function")) {9               varthen =Val.then;Ten               if(typeofthen = = = "function") { OneThen.call (Val,function(val) { A Res (I, Val); - }, reject); -                 return; the               } -             } -Args[i] =Val; -             if(--remaining = = 0) { + resolve (args); -             } +}Catch(ex) { A reject (ex); at           } -         } -          for(vari = 0; i < args.length; i++) { - Res (i, args[i]); -         } -       }); in};

As can be seen from the above, when the parameter of all is empty (args.length = = = 0), an iterative object of the Resolve method is returned. If it is not empty, and the all method is not promise on the array, then output value args[i] = Val, that is, S says return the initial value pending. If the array item of the All method is promise, it will callback resolve () and return the result of each item.

Example:

1 var promise = Promise.resolve (3); 2 promise.all ([True, Promise]). Then (values = {3   //  [ True, 3]4 });

promise.race ([])

SOURCE Analysis:

 1  promise.race = function   2  return  new  Promise (function   (resolve, reject) { 3  values.foreach (function   4   Promise.resolve (value). Then (resolve, reject);  5  });  6  });  7 }; 

In fact, the race method inside the array each item if all uses the Promise resolve method to implement the iteration, then each item in the array promise the state will send the change, just like race English meaning "race, competition", Indicates promise which item executes the resolve callback first, which promise executes the callback function first and returns the resolve result.

Example:

1 varP1 =NewPromise (function(Resolve, reject) {2SetTimeout (Resolve, "one");3 });4 varP2 =NewPromise (function(Resolve, reject) {5SetTimeout (Resolve, Max, "both");6 });7 8Promise.race ([P1, p2]). Then (function(value) {9Console.log (value);//"both"Ten   //Both Resolve, but P2 is faster One});

Reference:

Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise# See also

1190000007032448#articleheader10

https://www.promisejs.org/api/

JavaScript: Understanding the Promise Method

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.