1.Promise is a new es6 syntax designed to address callback hell. What is callback hell?

We found that the above code made heavy use of the callback function (passing one function as an argument to another) and had many}) ending symbols, which made the code look confusing.Copy the code
function callbackFn(callback) { setTimeout(function () { callback() }, 1000) } callbackFn(function () { callbackFn(function () { callbackFn(function () { callbackFn(function () { Console. log(' callback ends ')})})})Copy the code

Common types of callback hell: timer callback Ajax callback FS read/write file callback and about asynchronous requests…

2. The first one uses ES6 Promise, which translates to a Promise to return data to you at a certain point in the future.

(1) So let’s look at traditional Ajax requests first

function ajaxFun(url) { var xhr = new XMLHttpRequest(); xhr.open("get", url, false); xhr.send(); Xhr.onreadystatechange = function () {if (xhr.readyState == 4&&xhr.status == 200) {// Return response data in text form xhr.responseText; // Return response data as XML var xmlData = xhr.responsexml; } else { console.log(http.responseState) } }; return textdata } console.log(ajaxFun('www.baidu.com'))Copy the code

(2) Use ES6 promise to encapsulate ajax requests

function ajaxFun(url) {
           return new Promise((resolve,reject)=>{
            var xhr = new XMLHttpRequest();
            xhr.open("get", url, false);
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                   resolve(xhr.responseText)
                } else {
                    reject(xhr.status)
                }
            };
           })
        }
      ajaxFun(url).then((value)=>{
          console.log(value)
      },(reason)=>{
          console.log(reason)
      })
Copy the code

Promise API

Promise is one of the solutions to callback hell, and we use the Promise syntax to solve the problem of callback hell, making code readable and maintainable (ES6 states that the Promise object is a constructor that generates Promise instances for all asynchrony).

A Promise has three states: Pending: an asynchronous thing is being executed; It’s either success or failure. You can only change your status once

This is a big pity. Through resove ()

You have Rejected my invitation. Through the reject ()

let p = new Promise(function (resolve, Resolve (' successful callback ') // reject(' failed callback ')}) //then accept 2 callbacks either successfully, P.chen ((value)=>{console.log(value)},(reason)=>{console.log(reason)}) // Catch Only one failed callback p.catch((reason)=>{console.log(reason)})Copy the code

(1) Resolve and reject (a property on a function object, not an instance property) promise.resolve ()

Promise.reject() Both functions return a Promise object

Promise.resolve:

Resolve (' ABC ') // string let p1= promise.resolve (123) Resolve (new Promise((resolve,reject)=>{resolve(11) // reject(22)})) console.log(p1) P1.then ((value)=>{console.log(value)},(reason)=>{console.log(reason)})Copy the code

Promise.reject:

Reject (521) let p= promise. Reject (' ABC ') let p= promise. Reject (' ABC ') let p= promise. new Promise((resolve,reject)=>{ resolve(22222) }) ) console.log(p) p.then((value)=>{console.log(value)},(reason)=>{console.log(reason)})Copy the code

(2) Then and catch on the Promise prototype object

Promise.prototype.then()

Promsie.prototype.catch()

1. The Promise constructor has two variables == resolve== reject that return asynchronous success. Used in conjunction with then and catch.

2. After the Promise instance is generated, you can use the THEN method to specify the Resolved and Rejected state callback functions, respectively.

3. Reject must pass into the second callback in THEN, and catch if there is no second callback in THEN.

4. The then method can take two callback functions as arguments. The first callback is called when the Promise object’s state changes to Resolved. The second callback is called when the Promise object’s state changes to Rejected. The second function is optional and does not have to be provided. Both of these functions accept as arguments a value passed from the Promise object