This is the first day of my participation in the More text Challenge. For details, see more text Challenge

What is a Promise

A Promise is an object that represents the end result, success or failure, of an asynchronous operation. This is very depressing. There are three states: pedding, fulfilled and rejected

Promise is a javaScript standard built-in object, and ES6 specifies that a Promise object is a constructor, which means that we can generate an instance of a Promise with new Promise.

Features of a Promise object

  1. The state of an object is unaffected. Only the result of an asynchronous operation can determine the current state, which cannot be changed by any other operation.
  2. Once the state changes, it doesn’t change again, and it can happen any time. This means that the state of a Promise object can only change from pedding to fulfilled, or from pedding to rejected.
  3. Once a Promise is created, it is executed immediately and cannot be canceled.
  4. Errors thrown internally by a Promise are not reflected externally. The callback function needs to be set if it needs to be reflected externally.
  5. When in the pedding state, it is impossible to know the current stage of progress (just started or about to complete).

What’s the use of promises

Promise is primarily used to solve the problem of callback hell, which means that we can use chained.then calls for multiple layers of nested callbacks. The code will be clean and clear.

How do you use the promise

👀 chestnuts:

const promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* Asynchronous operation succeeded */){
    resolve(value);
  } else{ reject(error); }});Copy the code

The Promise constructor takes a function as an argument, which in turn takes two arguments, the resolve function that succeeds and the reject function that fails. The resolve and reject functions are provided by the JS engine.

The THEN method can be called after the instance is generated. Specifies callbacks for the Resolved and Rejected states.

promise.then(function(value) {
  // success
}, function(error) {
  // failure
});
Copy the code

So, here’s a simple js execution sequence interview question:

let promise = new Promise(function(resolve, reject) {
  console.log('Promise');
  resolve();
});

promise.then(function() {
  console.log('resolved.');
});

console.log('Hi! ');

// Promise
// Hi!
// resolved
Copy the code

In the above code, the Promise is created and executed immediately, so the Promise is printed first, followed by Hi! When the synchronization code is executed. When all the synchronized code is executed, the callback function specified by then is executed and output resolved.

  • PS: Is it possible to implement a promise’s Ajax?

The realization idea is simple as follows:

  1. The first thing we need to know to make a web request is that it should be _ajax(URL, params), which means it must have the request address and the request parameter (optional)
  2. Since a promise can be chained to a THEN method, the return value of the then method _ajax must be a Promise object

At this point we have the general frame

function _ajax(url, params){
    const promise = new Promise(a);return promise;
}
Copy the code
  1. Next, let’s enrich the contents:
  2. New a promise that takes a function as an argument
  3. This function takes two arguments, resolve and reject, which are two functions provided by the JS engine
function _ajax(url, params){
    function fn(resolve, reject){}const promise = new Promise(fn);
    return promise;
}
Copy the code
  1. I’m going to create an XHR object which is new XMLHttpRequest()
  2. It then binds the onReadyStatechange event to handle changes to XHR’s readyState property
  3. Next,.open() opens the connection and sets the request mode, the request address, and whether the request is asynchronous or synchronous
  4. You can then add the HTTP request header fields using setRequestHeader(k, v)
  5. Then.send(params) sends the request
function _ajax(url, params){
    function fn(resolve, reject){
        const xhr = new XMLHttpRequest();
        const handleChange = function (){
          
        }
        xhr.onreadystatechange = handleChange;
        xhr.responseType = "json";
        xhr.setRequestHeader("Accept".'application/json');
        xhr.open('POST', url);
        xhr.send(params);
    }
    const promise = new Promise(fn);
    return promise;
}
Copy the code
  1. That’s basically done, so let’s refine the event handler onReadyStatechange in detail
  2. ReadyState:
    • 0: Initialization has not started and open has not been called
    • 1: Open is called but send is not called
    • 2: Send is called, but the server does not respond
    • 3: The server is receiving the response, but the reception is not complete. Generally, no processing is performed here
    • 4: At this time, the response from the server has been received and the data can be processed
  3. Status Indicates that the status code is 200
function _ajax(url, params){
  params = JSON.stringify(params);
  function fn(resolve, reject){
    const xhr = new XMLHttpRequest();
    const handleChange = function (){
      if(this.status === 200 && this.readyState === 4){
        resolve(this.response)
      } else {
        reject(new Error(this.statusText))
      }
    }
    xhr.onreadystatechange = handleChange;
    xhr.responseType = "json";
    xhr.setRequestHeader("Accept".'application/json');
    xhr.open('POST', url);
    xhr.send(params);
  }
  const promise = new Promise(fn);

  return promise;
} 
Copy the code
  1. At this point, our Ajax based on promise is complete
  2. Perfect!