Category:javascript
Article From:https://www.cnblogs.com/jkCaptain/p/9059982.html

Preface

Promise It is a solution to asynchronous programming, which writes asynchronously with similar synchronous code. Children’s shoes that have touched setTimeout or Ajax before returning to hell should be deeply appreciated.

You can imagine Promise as a closed state machine, calling different callbacks and changing the state of Promise objects according to the success of asynchronous operations. When an asynchronous operation is successful, call resolve and call reject when it fails.

 

Advantage

① Stronger than callbacks and events, code is easier to read.

② Promise The constructor takes a function as a parameter. The two parameters of the function are reslove and reject respectively. These two parameters, also functions, are provided by the JavaScript engine. We just need to pass in these two parameters, then call them, without writing r themselves.Esolve or reject functions.

const p = new Promise((resolve, reject) => {
    resolve('ok');
})

 

shortcoming

① Promise It can’t be cancelled. New after a Promise instance, the code will be executed immediately and cannot interrupt halfway.

② Promise An internal throw error (throw or code error), if Promise’s catch is used to capture, Promise’s catch can be captured, but it does not react to the outside, that is, the console won’t throw the error.

 

Characteristic

① PromiseOnce the state of the object is changed, it will not change again.

② then The return is a new Promise instance. When the then chain is called, if the Promise object is returned in the then, then the latter then will wait for the Promise state in the previous then to change.It will be executed.

③ catchIt is used to capture reject status or error thrown in code. It returns a Promise object, which is equivalent to then’s syntax sugar – then (null, reject). So catch can be re connectedThen.

④ resolve The code after the reject code segment will still be executed. And it will be executed first than the code inside the then.

 Why will it be carried out first? Because of the event cycle mechanism, the event cycle mechanism has two main points of knowledge: macroTask (body code and setTimeout, etc.) and microTask (Promise and proces)S.nextTick etc.). Specific contents refer to the answers of users. I think it’s better.

new Promise((resolve, reject) => {
     resolve(1);
     console.log(2);
}).then(r => {
    console.log(r);
});
console.log(3);
// 2
// 3
// 1

⑤ fanally The function can refer to try – catch- fanally whether resolve or reject.

Application

The introduction of basic knowledge is over. Next, let’s see how to use it.

Common usage:

 ① Promise Encapsulation Ajax

const fetch = url => {
    const promise = new Promise((resolve, reject) => {
        const handler = function(){
            if (this.readyState !== 4) {
                return;
            }
            if (this.status === 200) {
                resolve(this.response);
            } else {
                reject(this.statusText);
            }
        }
        const xhr = new XMLHttpRequest();
        xhr.open('get', url);
        xhr.onreadystatechange = handler;
        xhr.send();
    });
    
    return promise;
}

② Load the picture

const getImage = url => {
    const promise = new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = resolve;
        img.onerror = reject;
        img.src = url;
    });
    return promise;
}

③ promise Sequence execution.

Sometimes, we have multiple requests, and there are dependencies between requests. For example, the next request depends on the data of the previous request. At this point, we need to execute sequentially, and we can encapsulate functions. (of course, it’s better to use async/await. )
Here I borrow the fetch function above (not the official fetch).

const createQueue = (...args) => args;

const firstReq = () => fetch('https://azu.github.io/promises-book/json/comment.json').then(JSON.parse);
const secondReq = () => fetch('https://azu.github.io/promises-book/json/people.json').then(JSON.parse);

const reqQueue = createQueue(firstReq, secondReq);
const start = (queue = []) => {
    // The data requested by two requests is merged into an array.
    const pushValue = (result => value => result = result.concat(value))([]);  
  // It is equivalent to Promise.resolve ().Then (firstReq).Then (pushValue).Then (secondReq).Then (pushValue).
return queue.reduce((promise, req) => promise.then(req).then(pushValue), Promise.resolve()); } start(reqQueue).then(value => console.log(value));

 

Static method

① Promise.resolve Convert existing objects to Promise objects, execute immediately and return a new promise instance. It is equivalent to new Promise (resolve => resolve ()). You can see es6-promISE

② Promise.reject Returns a new Promise instance whose status is rejected

③ Promise.race A number of Promise instances are packaged into a new Promise instance. As long as a Promise instance resolve, the next step is implemented.

④ Promise.all    A number of Promise instances are packaged into a new Promise instance. You need all Promise instance resolve or a Promise instance reject to execute the next step.

⑤ Promise.try  It is not understood for the time being.

 

summary

① Any asynchronous operation can use Promise, only when resolve is successful when the asynchronous operation is successful.

② catch Then you can pick up then again.

 

Reference resources

http://es6.ruanyifeng.com/#docs/promise

http://liubin.org/promises-book/#promise-sequence

Link of this Article: Promise- basic knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *