Promise learning objects ES6

1. What is the Promise objects?

Promise is asynchronous programming a solution than traditional solutions - more rational and more powerful - callback functions and events. Promise provides native objects. Promise event simply is a container, which holds only after execution. Level, grammar, Promise is an object, you can get messages from the asynchronous operation of it. Promise to provide a unified API, a variety of asynchronous operations can be handled the same way.

Features 2.Promise object

(1) First Promise object's state free from outside influence. Second promise object represents an asynchronous operation, there are three states: pending(ongoing), fulfilled(been successful) and rejected(failed). Only results of asynchronous operations, you can decide what kind of current state, no other operations can change that state.

(2) Once the status change, will not change, at any time this result can be obtained. PromiseState of the object changes, only two possibilities: from pendingchanges to fulfilledand from pendingturns rejected. As long as these two things happens, the state is fixed, and will not be changed and will keep the result, then called resolved (finalized). If the change has occurred, you again Promiseadd an object callback function will immediately get this result.

3.Promise usage

 1. The basic syntax is as follows:

            
            var Promise = new new Promise ( function (Resolve, Reject) {
               // ... some code 
              IF ( / * code execution success * / ) { 
                Resolve (value); 
              } the else { 
                Reject (error); 
              } 
            }); 
            Promise 
            . the then ( function () { 
                 / * code following the successful implementation * / 
            }) 
            . the catch ( function () {
                 / * code following the failed * /
            })

Parameter () is a function of Promise, which is a function of two parameters resolve the other reject, these two parameters are the type of function,

Function is to resolve the role of the state of the object from Promise "unfinished" to "success" (i.e., changed from pending resolved), upon successful call asynchronous operation, and the result of the asynchronous operation, then passed as a parameter to Methods.

rejectFunction returns the Promiseobject's state from "not completed" to "failed" (i.e., changed from pending Rejected), invoked when an asynchronous operation fails, and the asynchronous operation errors may be passed as a parameter to the method of catch .

The next move is a chestnut:

<script>
            var promise = new Promise(function(resolve, reject) {
                var num = Math.ceil(Math.random() * 100);
                console.log('num', num);
                if (num % 2 == 0) {
                    console.log('resolve', num);
                    resolve(num);
                } else {
                    console.log('reject', num);
                    reject(num);
                }
            });
            promise.then(function(num) {
                    console.log('then', num);
                })
                .catch(function(num) {
                    console.log('catch', num);
                })
            console.log('Hi!');
        </script>

Its output is:

 

 'Then' is only after the asynchronous call to the Promise, promise when the object defined execution back again so that the output of the 'num', after the execution order output 'Hi! '.

The Then () method using:

  then () method is mainly used to resolve the received parameters to pass out, then in fact there is also a function of the second parameter type, the second parameter is optional, it is used to reject reception parameter passed out.

It is worth mentioning that the then () method is back in a new Promise objects, which means support then chain method calls. For the first chestnuts:

    <script>
            var promise = new Promise(function(resolve, reject) {
                var num = Math.ceil(Math.random() * 100);
                console.log('num', num);
                if (num % 2 == 0) {
                    console.log('resolve', num);
                    resolve(num);
                } else {
                    console.log('reject', num);
                    reject(num);
                }
            });
            promise.then(function(num) {
                    console.log('then', num);
                    return 1;
                }).then(function(num){
                    console.log('then1', num);
                })
                .catch(function(num) {
                    console.log('catch', num);
                    return 11;
                })
            console.log('Hi!');
        </script>
    

Output is as follows:

 

 Returns the value of the first transfer function is then passed as a parameter to the second then to the second then the method.

the catch () method using:

If the asynchronous operation throws an error, status changes rejected, will call the catchmethod specified callback function, to deal with this error. Different methods of catch and then chained method calls are not supported.

the finally () method using:

finallyRegardless of the method used to target Promise final state, the operation will be performed specified. The method does not accept any parameters, can not accept the argument Promise to pass out, either resolve or method of passing parameters reject methods do not work.

 

Guess you like

Origin www.cnblogs.com/lin494910940/p/12443445.html
Recommended