Reading Notes: in-depth understanding ES6 (XI)

Chapter XI Promise and asynchronous programming

  Promise can be achieved in other similar language and Future Deferred same function, asynchronous programming is another option which can be specified later execution of code as an event and a callback function, as can clearly indicate whether the code is executed successfully.

 

Section 1 asynchronous programming background

  1. Mechanism

    JavaScript engine is based on the concept of a single thread (Single-threaded) event loop construction, i.e. the same time allowing only a block of code execution. These code blocks are placed in a task queue (job queue), every time a code is ready to execute, will be added to the task queue. Whenever the JavaScript engine in the end section of code is executed, the event loop (event loop) will perform the next task in the queue. JavaScript engine event loop is a piece of code, code execution is responsible for monitoring and managing task queue.

  2. Event Model

    Such as clicking a button or pressing the keyboard keys onclick event will be triggered, JavaScript is the most basic form of asynchronous programming. Although the event model is applicable to respond to user interaction and completion of similar low-frequency function, but for more complex needs is not very flexible.

  3. callback mode

    Correction mode and event model is similar to asynchronous code will be executed at a future time, is the difference between the two modes is called the callback function is passed as a parameter. E.g:

1 readFile("example.txt", function(err, contents) {
2     if (err) {
3         throw err;
4     }
5     console.log(contents);
6 });
7 console.log("Hi");

    In contrast, the callback mode is more flexible than the event model, but want to achieve more complex functions, limitations callback function will also emerge.

 

Basics of Section 2 Promise

  Promise asynchronous operation results equivalent to a placeholder, which do not subscribe to an event, it will not pass a callback function to the target parameters, but let the function returns a Promise. E.g:

1  // readFile promised a certain time within the next 
2 the let Promise = readFile ( "example.txt");

  1. Promise statement cycle

    a) Promise is performed first state (Pending), in which case the operation has not been completed; Once asynchronous operation execution ends, it becomes Promise processed (settled) state. Divided into the following two states:

    

    b) when the Promise of state changes, call then () method to take specific actions.

      the then () method takes two parameters: a first parameter is a function to be called when becomes fulfilled, the second is a function to call when the state becomes rejected.

      Another Promise the catch () method, corresponding to the then () method which is only to reject incoming handler.

 

  2. Create unfinished Promise

    You can create a new Promise with Promise constructor that takes one parameter function: Promise comprises performing initialization code (Executor) function. Actuator accepts two parameters, namely the resolve () function to call upon successful completion of execution, execution fails, call reject () function.

    Effector function is executed immediately before execution of the code in the subsequent process (i.e. resolve () / reject () is put into the re-execution task queue).

 

  3. Create processed Promise

    Use Promise.resolve () / Promise.reject () to create a Promise to achieve resolved according to a specific value. E.g:

1 let promise = Promise.resolve(42);
2 promise.then(function(value) {
3     console.log(value); //42
4 });
5 
6 let promise = Promise.reject(42);
7 promise.catch(function(value){
8     console.log(value); // 42
9 });

 

  4. Perform the error

    Each actuator implicitly in a try-catch block, the error will be caught and passed reject handler.

 

Section 3 of the global processing refuse Promise

  If the case did not refuse handlers, refused a Promise, then no message. Promise determine the characteristics of difficult to detect whether a Promise to be treated. Node.js browser and some changes were made to solve this developer pain points.

  1. refuse processing environment Node.js

    In Node.js, the processing will trigger two events on the Promise objects Promise rejected:

    · UnhandledRejection in an event loop, when the Promise was rejected, and does not provide refuse handler, the event is triggered.

    · RejectionHandled after an event loop, when Promise is rejected, if rejected handler is invoked, triggered the event.

    DETAILED code reference P.249

 

  2. refuse to deal with browser environment

    a) Browser untreated refuse is identified by two triggering events, although these events are triggered on the window object, but in virtually completely equivalent Node.js.

      · UnhandledRejection in an event loop, when the Promise was rejected, and does not provide refuse handler, the event is triggered.

      · RejectionHandled after an event loop, when Promise is rejected, if rejected handler is invoked, triggered the event.

    b) In Node.js implementation, the event handler accepts a plurality of parameters; in a browser, the event handler accepts an event object as a parameter has the following properties:

      · Type event name ( "unhandledReject" or "rejectionHandled");

      · Promise rejected Promise objects

      · Reason to refuse from the value of Promise

    c) different from another browser implementations that can be used to refuse values ​​(reason) in the two events. Code reference: P.251

 

Section 4 series Promise

  As a rule: Only after the first Promise or complete denial, the second will be resolved.

  1. Capture error

    It may also occur at the completion of error processing program and the processing program rejection, and can be used to capture the chain Promise these errors.

    Chain Promise calls can be perceived in other Promise chain of errors.

 

  2. Promise return value chain

     Another important feature is the chain Promise Promise to the downstream data transfer. In the completion handler and the handler can refuse to do so.

       Code reference P.255

 

  3. Return Promise Promise in the chain

    Promise actuator define the first execution, after the implementation of the definition.

 

Section 5 in response to a plurality of Promise

  Before telling the single Promise response. If you want to determine the next action by monitoring a plurality of Promise, may be used provided Promise.all ES6 () and Promise.race () method to monitor a plurality of two Promise.

  1. Promise.all () method

    This method only accepts one parameter and returns a Promise, which is more than one parameter monitored Promise iterable containing only after iterables all Promise are resolved, the return of Promise will be solved only when available All Promise iteration object are returned after the completion of the Promise will be completed.

    Among them, there are two cases:

    

 

     We look at these two cases, respectively, how to deal with:

       1. After all of the iterations objects are resolved and returned Promise, Promise kept inside the final values ​​are stored in the order of incoming Promise parameter array. E.g:

 1 let p1 = new Promise(function(reolve, reject) {
 2     resolve(42);
 3 });
 4 
 5 let p2 = new Promise(function(resolve, reject) {
 6     resolve(43);
 7 });
 8 
 9 let p3 = new Promise(function(resolve, reject) {
10     resolve(44);
11 });
12 
13 let p4 = Promise.all([p1, p2, p3]);
14 
15 p4.then(function(value) {
16     console.log( Array.isArray(value) ); // true
17     console.log( value[0] ); // 42
18     console.log( value[1] ); // 43
19     console.log( value[2] ); // 44
20 });

      2. When there is an iteration object Promise rejected, as long as one is rejected, did not wait for all the returned Promise Promise is done immediately be rejected, such as:

 1 let p1 = new Promise(function(reolve, reject) {
 2     resolve(42);
 3 });
 4 
 5 let p2 = new Promise(function(resolve, reject) {
 6     reject(43);
 7 });
 8 
 9 let p3 = new Promise(function(resolve, reject) {
10     resolve(44);
11 });
12 
13 let p4 = Promise.all([p1, p2, p3]);
14 
15 p4.then(function(value) {
16     console.log( Array.isArray(value) ); // true
17     console.log( value ); // 43
18 });

 

  2. Promise.race()方法

    Promise.race () and Promise.all () is slightly different. In iterables, as long as there is a Promise is resolved, the return of Promise solved without Promise wait until all are completed.

    If the first solution is to have completed Promise, then return the completed Promise; if the first solution is to have rejected Promise, has refused to return to the Promise. Look at an example:

 1 let p1 = new Promise(function(resolve, reject) {
 2     setTimeout(function() {resolve(42);}, 0);
 3 });
 4 
 5 let p2 = Promise.reject(43);
 6 
 7 let p3 = new Promise(function(resolve,reject) {
 8     resolve(44)
 9 });
10 
11 let p4 = Promise.race([p1, p2, p3]);
12 
13 p4.catch(function(value) {
14     console.log(value); // 43
15 });

 

Section 6 inherited from Promise

  Promise is a base class, because you can derive other classes.

  Examples of reference code P.262

 

Section 7 of asynchronous task execution based Promise

  Each long as asynchronous operation returns Promise, Promise to as common interface for all asynchronous code may simplify the task executor.

  Examples of reference code P.265

 

(End of this section)

Guess you like

Origin www.cnblogs.com/zxxsteven/p/11518826.html