Detailed ES6's Promise

Foreword

Promise, to solve the problem caused by the callback area, the operation asynchronous operation to synchronous programming express, avoid deeply nested callback function.

What is Promise

The so-called promise, simply means that a container, which holds an event in the future will be the end (that is, our asynchronous operation) results. For the above grammar, Promise is an object, the message may be obtained from its asynchronous operation. Promise to provide a unified API, a variety of asynchronous operations can be handled the same way.

Promise properties

  • promise object represents an asynchronous operation, there are three states: pending, fulfilled, reject
  • Any other state can change that state. This is also the origin of the name of Promise. 'Commitment' means other means can not change its state.

Promise appear to solve any problem

promise asynchronous programming is actually a program, there will always appear before the promise of nested code for so-called 'back out area' of

    step(1, function() {
        step(2, function() {
            step(3, function() {
                ……….
            })
        })
    })

We know that this "callback hell", is a very angry people writing the code format, will make people suspect read up life after nested layers. But this "callback hell" Really the only problem incorrect format? Obviously not.

Examples of references

An example from "YDKJS": A programmer has developed a payment system, which is a good run for a long time. Suddenly one day, a customer at the time of payment credit card was continuous brush five times. The programmer's investigation later found that a third-party tool library for some reason the payment callback performed five times. After communication with third-party team problem has been resolved.

Way above example is a problem of trust callback function will lead to a lot of trust issues, such as repeated call, the call too late and so on. So how promise to solve these two problems?

Promise significance

  • Readability
    first method is then Promise, supporting us in writing then the callback method, so that we can clearly see in the daily development, such as the above code can be rewritten as
     Promise.resolve(1).
     .then(step => ++setp)
     .then(step => ++setp)
     .then(step => ++setp)
 ...

  • Rigor Promise commitments
    difference between it and the way that ordinary callback

General way , the success of the operation after the callback written directly inside a callback function to invoke these operations are controlled by a third party

Promise way callback is only responsible for notification after success, and the success of the operation after the callback callback function then placed inside, precise control of the Promise.

Note Promise state is irreversible. Once the change is no way to change into any state. Promise only be asynchronous, synchronous asynchronous call does not occur.

Promise shortcomings

  • New Promise can not be canceled once it will be executed immediately, can not be canceled during
  • If you do not set a callback function, internal Promise thrown error does not react to the outside.
  • When in pending state, currently no way of knowing where to stage (beginning or the end)

How to use the Promise

Promise object is a constructor to generate instances Promise

Promise a constructor function receives as a parameter, two parameters are the function resolve and reject, these two parameters are functions provided by the JavaScript, no need to add their own

After generating Promise example, you can specify a callback function resolved state by state and then rejected Methods. But then generally not recommended to add two parameters recommended .then finished resolved state, using the .catch finished rejected. like this:

    const promise = new Promise( (resolve,reject) => {
        resolve('ok');
        reject('error')
    })
    promise.then(res => {
        console.log(res)
    }).catch(err => {
        console.log(err)
    })

Ajax operations may also be implemented with a promise:

const getJSON = function(url){
        const promise = new Promise((resolve,reject) => {
            const handler = function(){
                if(this.readyState !== 4){//这两个if语句主要用来判断请求是否成功
                    return;
                };
                if(this.status === 200){
                    resolve(this.response)//这是成功请求后,将返回的数据传到回调函数中
                }else{
                    reject(new Error(this.statusText))//这是失败后,将原因返给catch
                }
            };
            const xmlHttp = new XMLHttpRequest();//声明一个XMLHttpRequest对象的实例
            xmlHttp.open("get", url);//设置要发送的方法和地址
            xmlHttp.onreadystatechange = handler;//在这里调用上面定义的handler
            xmlHttp.responseType = "json";
            xmlHttp.setRequestHeader("Accept", "application/json");//设置请求头,规定接受json类型的数据
            xmlHttp.send();//真正的发送请求
        });
        return promise;
    };
    getJSON("url").then( res => {
        //成功后的操作
    }).catch(err => {
        //失败后的提示
    })

Promise can be nested, it is to resolve a Promise As another example of the method of Example Promise parameter.

Then talk about the method, which is defined on a prototype Promise, then the method returns a new Promise instance, can be written using the chain, then the latter method i.e. then calls another method.

Let me now several common api Promise it!

Promise.prototype.finally():

Finally a method for operating Whatever the final status of promise object will be executed

promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});

Promise.resolve():

  • This method is used to convert the parameter to a target Promise
  • Promise parameter is an example: no change
  • Parameter is a thenable objects: This object will be converted Promise object and then immediately execute method thenable object.
  • Then the argument is not an object has a method, or is simply not an object: Returns a new Promise object status is resolved
  • Promise ersolved object directly returns a status: no parameters

Promise.reject () Promise.reject (reason) method also returns a new Promise instance, the state of the instance is rejected

Promise.all():

    const p = Promise.all([p1, p2, p3]);

Promise for the plurality of instances, packaged into a new instance Promise. This method receives an array as a parameter, and are Promise example, the method if not, it will first call Promise.resolve. Note: Only when an instance of the array are Fulfilled state, will become a p Fulfilled, at this time, p1, p2, p3 composed of an array of the return value, p is passed to the callback function. Among long p1, p2, p3 is a Rejected, the state becomes the p Rejected, return values ​​at this time is the first instance of the reject, is passed to the callback function p.

Promise.race (): and the like all methods, is speaking into a plurality of packaged Promise instances. But not the same, as long as there is one instance among p1, p2, p3 lead changes state, the state p to change with it. Promise to return the value of that instance of the first to change, it is passed to the callback function p.

In the actual development, we always want to make the synchronization function executed synchronously, asynchronously perform asynchronous function, but if you want to use synchronous functions Promise to do processing, can synchronize it? The answer is yes. This comes to Promise.try () method of

    const f = () => console.log('now');
    Promise.try(f);
    console.log('next');
// now// next

image

Published 35 original articles · won praise 64 · views 10000 +

Guess you like

Origin blog.csdn.net/tjx11111/article/details/104390323