Callbacks are the foundation of asynchronous programming in Javascript, and if we use traditional methods to implement complex asynchronous processes, it’s easy to form a callback hell, which can be very inelegant to implement and difficult to maintain. So, is there a solution to this problem? The answer is yes. ES2015 provides a specification to solve this problem, called a Promise.

Basic use of Promise

Promise accepts a function that takes two arguments, a successful resovle and a failed reject.

Const promise = new Promise(function (resolve, reject) {resolve(" succeed "); / / reject (" failure "); }) promise.then(function (value) { console.log("resolve", value); }, function (error) {console.log("reject", error); })Copy the code

In this example, we call promise’s then method, which takes two arguments. The first corresponds to the resolve method defined above, which we can implement after a success, and the second corresponds to the resolve method defined above, which we can implement after a failure. Note that the two parameters we pass in when we define the Promise have only one outcome, either success or failure. As shown in the figure below:

Const promise1 = new Promise(function (resolve, reject) {resolve(" success "); Reject (" failure "); }) promise.then (function (value) {console.log("resolve", value) // resolve successfully}, function (error) { console.log("reject", error); }) const promise2 = new Promise(function (resolve, reject) {//resolve(" success "); Reject (" failure "); Then (function (value) {console.log("resolve", "reject")}, function (error) {console.log("reject", "reject") error); // reject failed})Copy the code

Encapsulate ajax requests

We can use promises to encapsulate Ajax requests by defining a method that returns a Promise.

function ajax (url) {
    return new Promise(function (resolve,reject ) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.responseType = 'json';
        xhr.onload = function () {
           if(this.status === 200) {
               resolve(this.response);
           } else {
               reject(new Error(this.statusText));
           }
        }
        xhr.send();
    })
}
 
ajax("XXXX").then(function (res) {
    console.log(res);
}, function (error) {
    console.log(error);
})
Copy the code

A common misconception with promises

A common mistake in using promises is nesting, such as when request 3 depends on the result of request 2, which in turn depends on request 1…… So, we might write it like this

ajax('api/users').then(function (user1) {
    ajax(user1).then(function (user2) {
        ajax(user2).then(function (user3) {
            ajax(user3).then(function () {
                
            })
        })
    })
})
Copy the code

It’s wrong to write this way. At this point, we can use promise’s chained calls to achieve flattening. Note that:

  • The THEN method on the Promise object returns an entirely new Promise object
  • The subsequent THEN method registers the callback for the Promise returned by the previous THEN
  • The return value of the callback function in the previous THEN method is taken as an argument to the later THEN method callback

The use method of chain call, and the catch method of exception is recommended. As follows:

ajax('api/users').then(function (value) {
   console.log('resolve',value);
   return ajax('/error-url');
}).catch(function (error) {
    console.log("error",error);
})
Copy the code

Promise parallel execution

Var promiseAll = promise.all ([ajax(' 1'), ajax(' 2')]) then(function (values) {console.log(values); Return console.log(values[0]); // Return an array of values if both requests are successful; Console. log(values[1]); }).catch(function (error) {console.log(error); })Copy the code

Finally, a Promise is executed in a microtask order and takes precedence over setTimeout execution.

Link: blog.csdn.net/weixin_4127…